google-id-token 1.3.1 → 1.4.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 65d747323f11a45f8a50cf6a4fc7c08de0bba49a
4
- data.tar.gz: aee5256465f70b690d83fcaee93a0036e3444e7c
3
+ metadata.gz: 24089c2c4e9bb86822d3c8530b92d91b43d5d9c1
4
+ data.tar.gz: '068251a4ac9a3e856881b8d6babeb36865145c4e'
5
5
  SHA512:
6
- metadata.gz: 5cf39a389110be3cdd99482fcb25840d7fcb8de85569a91eba39e54d83dc321ea9a64e162fd7f8b081ce50a82b799ad8ec0229a4d9cbd89faab323efbb10f901
7
- data.tar.gz: df6376c1d08aee4f11943920d56ba358293991302747ba5b45a238e654ce0b8bf108b09aefb05d6f4fa71c3c985070359120830e0ab259d50389e2bc1ccf094c
6
+ metadata.gz: 332ef6d84f3a1b2cb008a8931d2d8389bd605f4d670ea7821cc8fd6cc31044fde7581f0d3d85a1417df34d06ec1b2fbc92a4af4e1db2d093ee7edce5467a8310
7
+ data.tar.gz: 27dd06d5c1b686699acb96b819c926a1f22a729d1b7c1a534821c6941a1f0c160112c4aca72ffe68f923affa940f5e0fb018d8d5c43e6f5826d0f94f14e6e9f9
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
@@ -0,0 +1,7 @@
1
+ ## [1.4.0] - 2017-01-20
2
+ ### Added
3
+ - Add `expiry` option to the `Validator` which defines the time after which the certificates cache should be renewed. This prevents continuously fetching them in case of constant decoding errors.
4
+
5
+ ### Changed
6
+ - Make `Validator` thread-safe by not maintaining error state. Errors in `#check` are not saved to the instance variable `problem`. Added specific error classes which are raised upon validation errors instead.
7
+ - Caching certificates in the `Validator` instead of always fetching them from Google servers.
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ # encoding: utf-8
2
+ source "https://rubygems.org"
3
+
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,55 @@
1
+ # GoogleIDToken
2
+
3
+ GoogleIDToken verifies the integrity of ID tokens generated by Google authentication servers.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'google-id-token'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install google-id-token
20
+
21
+ ## Usage
22
+
23
+ GoogleIDToken currently provides a single useful class `Validator`, which provides a single method `#check`, which parses and validates the integrity of an ID Token allegedly generated by Google auth servers.
24
+
25
+ ```ruby
26
+ validator = GoogleIDToken::Validator.new
27
+ begin
28
+ payload = validator.check(token, required_audience, optional_client_id)
29
+ email = payload['email']
30
+ rescue GoogleIDToken::ValidationError => e
31
+ report "Cannot validate: #{e}"
32
+ end
33
+ ```
34
+
35
+ ## Configuration
36
+
37
+ Creating a new validator takes a single optional hash argument. If the hash has an entry for :x509_key, that value is taken to be a key as created by OpenSSL::X509::Certificate.new, and the token is validated using that key. If there is no such entry, the keys are fetched from the Google certs endpoint https://www.googleapis.com/oauth2/v1/certs. The certificates are cached for some time (default: 1 hour) which can be configured by adding the :expiry argument to the initialization hash (in seconds).
38
+
39
+ ### expiry
40
+
41
+ Expiry defines the the time (in seconds) in which the cached Google certificates are valid.
42
+
43
+ ```ruby
44
+ GoogleIDToken::Validator.new(expiry: 1800) # 30 minutes
45
+ ```
46
+
47
+ ### x509_cert
48
+
49
+ x509_cert can be provided to manually define a certificate to validate the tokens.
50
+
51
+ ```ruby
52
+ cert = OpenSSL::X509::Certificate.new(File.read('my-cert.pem'))
53
+ validator = GoogleIDToken::Validator.new(x509_cert: cert)
54
+ ```
55
+
@@ -0,0 +1,22 @@
1
+ # encoding: utf-8
2
+ # Copyright 2012 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the "License");
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an "AS IS" BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+
16
+
17
+ require 'bundler/gem_tasks'
18
+ require 'rspec/core/rake_task'
19
+
20
+ task :default => :spec
21
+
22
+ RSpec::Core::RakeTask.new
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "google-id-token"
5
+
6
+ require "irb"
7
+ IRB.start
@@ -0,0 +1,6 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
@@ -0,0 +1,40 @@
1
+ # encoding: utf-8
2
+ # Copyright 2012 Google Inc.
3
+ #
4
+ # Licensed under the Apache License, Version 2.0 (the 'License');
5
+ # you may not use this file except in compliance with the License.
6
+ # You may obtain a copy of the License at
7
+ #
8
+ # http://www.apache.org/licenses/LICENSE-2.0
9
+ #
10
+ # Unless required by applicable law or agreed to in writing, software
11
+ # distributed under the License is distributed on an 'AS IS' BASIS,
12
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ # See the License for the specific language governing permissions and
14
+ # limitations under the License.
15
+ lib = File.expand_path('../lib', __FILE__)
16
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
17
+ require 'google-id-token/version'
18
+
19
+ Gem::Specification.new do |s|
20
+ s.name = 'google-id-token'
21
+ s.version = GoogleIDToken::VERSION
22
+
23
+ s.homepage = 'https://github.com/google/google-id-token/'
24
+ s.license = 'APACHE-2.0'
25
+ s.summary = 'Google ID Token utilities'
26
+ s.description = 'Google ID Token utilities; currently just a parser/checker'
27
+
28
+ s.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
29
+ s.require_paths = ["lib"]
30
+
31
+ s.add_runtime_dependency 'jwt', '>= 1'
32
+
33
+ s.add_development_dependency 'fakeweb'
34
+ s.add_development_dependency 'rake'
35
+ s.add_development_dependency 'rspec'
36
+ s.add_development_dependency 'openssl'
37
+
38
+ s.authors = ['Tim Bray', 'Bob Aman']
39
+ s.email = 'tbray@textuality.com'
40
+ end
@@ -18,29 +18,42 @@
18
18
  # succeeds, returns the decoded ID Token as a hash.
19
19
  # It's a good idea to keep an instance of this class around for a long time,
20
20
  # because it caches the keys, performs validation statically, and only
21
- # refreshes from Google when required (typically once per day)
21
+ # refreshes from Google when required (once per day by default)
22
22
  #
23
23
  # @author Tim Bray, adapted from code by Bob Aman
24
24
 
25
- require 'multi_json'
25
+ require 'google-id-token/version'
26
+ require 'json'
26
27
  require 'jwt'
27
- require 'openssl'
28
+ require 'monitor'
28
29
  require 'net/http'
30
+ require 'openssl'
29
31
 
30
32
  module GoogleIDToken
33
+ class CertificateError < StandardError; end
34
+ class ValidationError < StandardError; end
35
+ class ExpiredTokenError < ValidationError; end
36
+ class SignatureError < ValidationError; end
37
+ class InvalidIssuerError < ValidationError; end
38
+ class AudienceMismatchError < ValidationError; end
39
+ class ClientIDMismatchError < ValidationError; end
40
+
31
41
  class Validator
42
+ include MonitorMixin
32
43
 
33
44
  GOOGLE_CERTS_URI = 'https://www.googleapis.com/oauth2/v1/certs'
45
+ GOOGLE_CERTS_EXPIRY = 3600 # 1 hour
34
46
 
35
- # @!attribute [r] problem
36
- # Reason for failure, if #check returns nil
37
- attr_reader :problem
47
+ # https://developers.google.com/identity/sign-in/web/backend-auth
48
+ GOOGLE_ISSUERS = ['accounts.google.com', 'https://accounts.google.com']
38
49
 
39
- def initialize(keyopts = {})
40
- if keyopts[:x509_cert]
50
+ def initialize(options = {})
51
+ super()
52
+
53
+ if options[:x509_cert]
41
54
  @certs_mode = :literal
42
- @certs = { :_ => keyopts[:x509_cert] }
43
- # elsif keyopts[:jwk_uri] # TODO
55
+ @certs = { :_ => options[:x509_cert] }
56
+ # elsif options[:jwk_uri] # TODO
44
57
  # @certs_mode = :jwk
45
58
  # @certs = {}
46
59
  else
@@ -48,14 +61,15 @@ module GoogleIDToken
48
61
  @certs = {}
49
62
  end
50
63
 
64
+ @certs_expiry = options.fetch(:expiry, GOOGLE_CERTS_EXPIRY)
51
65
  end
52
66
 
53
67
  ##
54
- # If it validates, returns a hash with the JWT fields from the ID Token.
68
+ # If it validates, returns a hash with the JWT payload from the ID Token.
55
69
  # You have to provide an "aud" value, which must match the
56
70
  # token's field with that name, and will similarly check cid if provided.
57
71
  #
58
- # If something fails, returns nil; #problem returns error text
72
+ # If something fails, raises an error
59
73
  #
60
74
  # @param [String] token
61
75
  # The string form of the token
@@ -64,82 +78,80 @@ module GoogleIDToken
64
78
  # @param [String] cid
65
79
  # The optional client-id ("azp" field) value
66
80
  #
67
- # @return [Hash] The decoded ID token, or null
81
+ # @return [Hash] The decoded ID token
68
82
  def check(token, aud, cid = nil)
69
- case check_cached_certs(token, aud, cid)
70
- when :valid
71
- @token
72
- when :problem
73
- nil
74
- else
75
- # no certs worked, might've expired, refresh
76
- if refresh_certs
77
- @problem = 'Unable to retrieve Google public keys'
78
- nil
79
- else
80
- case check_cached_certs(token, aud, cid)
81
- when :valid
82
- @token
83
- when :problem
84
- nil
83
+ synchronize do
84
+ payload = check_cached_certs(token, aud, cid)
85
+
86
+ unless payload
87
+ # no certs worked, might've expired, refresh
88
+ if refresh_certs
89
+ payload = check_cached_certs(token, aud, cid)
90
+
91
+ unless payload
92
+ raise SignatureError, 'Token not verified as issued by Google'
93
+ end
85
94
  else
86
- @problem = 'Token not verified as issued by Google'
87
- nil
95
+ raise CertificateError, 'Unable to retrieve Google public keys'
88
96
  end
89
97
  end
98
+
99
+ payload
90
100
  end
91
101
  end
92
102
 
93
103
  private
94
104
 
95
105
  # tries to validate the token against each cached cert.
96
- # Returns :valid (sets @token) or :problem (sets @problem) or
106
+ # Returns the token payload or raises a ValidationError or
97
107
  # nil, which means none of the certs validated.
98
108
  def check_cached_certs(token, aud, cid)
99
- @problem = @token = @tokens = nil
109
+ payload = nil
100
110
 
101
111
  # find first public key that validates this token
102
112
  @certs.detect do |key, cert|
103
113
  begin
104
114
  public_key = cert.public_key
105
- @tokens = JWT.decode(token, public_key, !!public_key)
106
- @tokens.each do |currtoken|
107
- # in Feb 2013, the 'cid' claim became the 'azp' claim per changes
108
- # in the OIDC draft. At some future point we can go all-azp, but
109
- # this should keep everything running for a while
110
- if currtoken['azp']
111
- currtoken['cid'] = currtoken['azp']
112
- if(currtoken.has_key?('aud') && (currtoken['aud'] == aud) &&
113
- currtoken.has_key?('cid') && (currtoken['cid'] == cid))
114
- # If we find a valid token, save it for further verification.
115
- @token = currtoken
116
- end
117
- elsif currtoken['cid']
118
- currtoken['azp'] = currtoken['cid']
119
- end
115
+ decoded_token = JWT.decode(token, public_key, !!public_key)
116
+ payload = decoded_token.first
117
+
118
+ # in Feb 2013, the 'cid' claim became the 'azp' claim per changes
119
+ # in the OIDC draft. At some future point we can go all-azp, but
120
+ # this should keep everything running for a while
121
+ if payload['azp']
122
+ payload['cid'] = payload['azp']
123
+ elsif payload['cid']
124
+ payload['azp'] = payload['cid']
120
125
  end
121
- rescue JWT::DecodeError
126
+ payload
127
+ rescue JWT::ExpiredSignature
128
+ raise ExpiredTokenError, 'Token signature is expired'
129
+ rescue JWT::DecodeError => e
122
130
  nil # go on, try the next cert
123
131
  end
124
132
  end
125
133
 
126
- if @token
127
- if !(@token.has_key?('aud') && (@token['aud'] == aud))
128
- @problem = 'Token audience mismatch'
129
- elsif cid && !(@token.has_key?('cid') && (@token['cid'] == cid))
130
- @problem = 'Token client-id mismatch'
134
+ if payload
135
+ if !(payload.has_key?('aud') && payload['aud'] == aud)
136
+ raise AudienceMismatchError, 'Token audience mismatch'
137
+ end
138
+ if cid && payload['cid'] != cid
139
+ raise ClientIDMismatchError, 'Token client-id mismatch'
131
140
  end
132
- @problem ? :problem : :valid
141
+ if !GOOGLE_ISSUERS.include?(payload['iss'])
142
+ raise InvalidIssuerError, 'Token issuer mismatch'
143
+ end
144
+ payload
133
145
  else
134
146
  nil
135
147
  end
136
148
  end
137
149
 
138
- # returns true if there was a problem
150
+ # returns false if there was a problem
139
151
  def refresh_certs
140
152
  case @certs_mode
141
153
  when :literal
142
- return # no-op
154
+ true # no-op
143
155
  when :old_skool
144
156
  old_skool_refresh_certs
145
157
  # when :jwk # TODO
@@ -148,18 +160,29 @@ module GoogleIDToken
148
160
  end
149
161
 
150
162
  def old_skool_refresh_certs
163
+ return true unless certs_cache_expired?
164
+
151
165
  uri = URI(GOOGLE_CERTS_URI)
152
166
  get = Net::HTTP::Get.new uri.request_uri
153
167
  http = Net::HTTP.new(uri.host, uri.port)
154
168
  http.use_ssl = true
155
169
  res = http.request(get)
156
170
 
157
- if res.kind_of?(Net::HTTPSuccess)
158
- new_certs = Hash[MultiJson.load(res.body).map do |key, cert|
159
- [key, OpenSSL::X509::Certificate.new(cert)]
160
- end]
171
+ if res.is_a?(Net::HTTPSuccess)
172
+ new_certs = Hash[JSON.load(res.body).map do |key, cert|
173
+ [key, OpenSSL::X509::Certificate.new(cert)]
174
+ end]
161
175
  @certs.merge! new_certs
176
+ @certs_last_refresh = Time.now
177
+ true
178
+ else
162
179
  false
180
+ end
181
+ end
182
+
183
+ def certs_cache_expired?
184
+ if defined? @certs_last_refresh
185
+ Time.now > @certs_last_refresh + @certs_expiry
163
186
  else
164
187
  true
165
188
  end
@@ -0,0 +1,3 @@
1
+ module GoogleIDToken
2
+ VERSION = "1.4.0".freeze
3
+ end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: google-id-token
3
3
  version: !ruby/object:Gem::Version
4
- version: 1.3.1
4
+ version: 1.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tim Bray
@@ -9,36 +9,22 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2015-12-11 00:00:00.000000000 Z
12
+ date: 2017-09-01 00:00:00.000000000 Z
13
13
  dependencies:
14
- - !ruby/object:Gem::Dependency
15
- name: multi_json
16
- requirement: !ruby/object:Gem::Requirement
17
- requirements:
18
- - - ">="
19
- - !ruby/object:Gem::Version
20
- version: '0'
21
- type: :runtime
22
- prerelease: false
23
- version_requirements: !ruby/object:Gem::Requirement
24
- requirements:
25
- - - ">="
26
- - !ruby/object:Gem::Version
27
- version: '0'
28
14
  - !ruby/object:Gem::Dependency
29
15
  name: jwt
30
16
  requirement: !ruby/object:Gem::Requirement
31
17
  requirements:
32
18
  - - ">="
33
19
  - !ruby/object:Gem::Version
34
- version: '0'
20
+ version: '1'
35
21
  type: :runtime
36
22
  prerelease: false
37
23
  version_requirements: !ruby/object:Gem::Requirement
38
24
  requirements:
39
25
  - - ">="
40
26
  - !ruby/object:Gem::Version
41
- version: '0'
27
+ version: '1'
42
28
  - !ruby/object:Gem::Dependency
43
29
  name: fakeweb
44
30
  requirement: !ruby/object:Gem::Requirement
@@ -101,11 +87,21 @@ executables: []
101
87
  extensions: []
102
88
  extra_rdoc_files: []
103
89
  files:
104
- - README.rdoc
90
+ - ".gitignore"
91
+ - ".rspec"
92
+ - CHANGELOG.md
93
+ - Gemfile
94
+ - LICENSE
95
+ - README.md
96
+ - Rakefile
97
+ - bin/console
98
+ - bin/setup
99
+ - google-id-token.gemspec
105
100
  - lib/google-id-token.rb
101
+ - lib/google-id-token/version.rb
106
102
  homepage: https://github.com/google/google-id-token/
107
103
  licenses:
108
- - Apache-2.0
104
+ - APACHE-2.0
109
105
  metadata: {}
110
106
  post_install_message:
111
107
  rdoc_options: []
@@ -123,7 +119,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
123
119
  version: '0'
124
120
  requirements: []
125
121
  rubyforge_project:
126
- rubygems_version: 2.2.2
122
+ rubygems_version: 2.6.8
127
123
  signing_key:
128
124
  specification_version: 4
129
125
  summary: Google ID Token utilities
@@ -1,29 +0,0 @@
1
- = GoogleIDToken
2
-
3
- GoogleIDToken currently provides a single useful class "Validator", which provides a single method "#check", which parses and validates an ID Token allegedly generated by Google auth servers.
4
-
5
- Creating a new validator takes a single optional hash argument. If the hash has an entry for :x509_key, that value is taken to be a key as created by OpenSSL::X509::Certificate.new, and the token is validated using that key. If there is no such entry, the keys are fetched from the Google certs endpoint https://www.googleapis.com/oauth2/v1/certs.
6
-
7
- === Installation
8
-
9
- gem install google-id-token
10
-
11
- === Examples
12
-
13
- validator = GoogleIDToken::Validator.new
14
- jwt = validator.check(token, required_audience, required_client_id)
15
- if jwt
16
- email = jwt['email']
17
- else
18
- report "Cannot validate: #{validator.problem}"
19
- end
20
-
21
-
22
- cert = OpenSSL::X509::Certificate.new(File.read('my-cert.pem'))
23
- validator = GoogleIDToken::Validator.new(:x509_cert => cert)
24
- jwt = validator.check(token, required_audience, required_client_id)
25
- if jwt
26
- email = jwt['email']
27
- else
28
- report "Cannot validate: #{validator.problem}"
29
- end