├── .circleci └── config.yml ├── .gitignore ├── .rspec ├── CHANGELOG.md ├── Gemfile ├── LICENSE ├── README.md ├── Rakefile ├── bin ├── console └── setup ├── google-id-token.gemspec ├── lib ├── google-id-token.rb └── google-id-token │ └── version.rb └── spec ├── google-id-token_spec.rb └── spec_helper.rb /.circleci/config.yml: -------------------------------------------------------------------------------- 1 | # Ruby CircleCI 2.0 configuration file 2 | # 3 | # Check https://circleci.com/docs/2.0/language-ruby/ for more details 4 | # 5 | version: 2 6 | jobs: 7 | build: 8 | docker: 9 | - image: circleci/ruby:2.4.1-node-browsers 10 | 11 | working_directory: ~/google-id-token 12 | 13 | steps: 14 | - checkout 15 | 16 | - run: 17 | name: install dependencies 18 | command: | 19 | bundle install 20 | 21 | # run tests! 22 | - run: 23 | name: run tests 24 | command: | 25 | bundle exec rake 26 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | /.bundle/ 2 | /.yardoc 3 | /Gemfile.lock 4 | /_yardoc/ 5 | /coverage/ 6 | /doc/ 7 | /pkg/ 8 | /spec/reports/ 9 | /tmp/ 10 | -------------------------------------------------------------------------------- /.rspec: -------------------------------------------------------------------------------- 1 | --format documentation 2 | --color 3 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | ## [1.4.2] - 2017-09-11 4 | ### Fxied 5 | - Updated `*.rb` files' file permissions. 6 | 7 | ## [1.4.1] - 2017-09-06 8 | ### Added 9 | - Add compatibility with `jwt` gem `v2.0`. 10 | 11 | 12 | ## [1.4.0] - 2017-09-01 13 | ### Added 14 | - 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. 15 | 16 | ### Changed 17 | - 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. 18 | - Caching certificates in the `Validator` instead of always fetching them from Google servers. 19 | -------------------------------------------------------------------------------- /Gemfile: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | source "https://rubygems.org" 3 | 4 | gemspec -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 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. 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # GoogleIDToken 2 | 3 | **The `google-id-token` gem is deprecated. Its functionality is now available in the `googleauth` gem.** 4 | 5 | See: 6 | 7 | * https://github.com/googleapis/google-auth-library-ruby. 8 | * https://rubydoc.info/gems/googleauth/Google/Auth/IDTokens 9 | -------------------------------------------------------------------------------- /Rakefile: -------------------------------------------------------------------------------- 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 23 | -------------------------------------------------------------------------------- /bin/console: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | require "bundler/setup" 4 | require "google-id-token" 5 | 6 | require "irb" 7 | IRB.start 8 | -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | set -euo pipefail 3 | IFS=$'\n\t' 4 | set -vx 5 | 6 | bundle install 7 | -------------------------------------------------------------------------------- /google-id-token.gemspec: -------------------------------------------------------------------------------- 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 41 | -------------------------------------------------------------------------------- /lib/google-id-token.rb: -------------------------------------------------------------------------------- 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 | # Validates strings alleged to be ID Tokens issued by Google; if validation 18 | # succeeds, returns the decoded ID Token as a hash. 19 | # It's a good idea to keep an instance of this class around for a long time, 20 | # because it caches the keys, performs validation statically, and only 21 | # refreshes from Google when required (once per day by default) 22 | # 23 | # @author Tim Bray, adapted from code by Bob Aman 24 | 25 | require 'google-id-token/version' 26 | require 'json' 27 | require 'jwt' 28 | require 'monitor' 29 | require 'net/http' 30 | require 'openssl' 31 | 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 | 41 | class Validator 42 | include MonitorMixin 43 | 44 | GOOGLE_CERTS_URI = 'https://www.googleapis.com/oauth2/v1/certs' 45 | GOOGLE_CERTS_EXPIRY = 3600 # 1 hour 46 | 47 | # https://developers.google.com/identity/sign-in/web/backend-auth 48 | GOOGLE_ISSUERS = ['accounts.google.com', 'https://accounts.google.com'] 49 | 50 | def initialize(options = {}) 51 | super() 52 | 53 | if options[:x509_cert] 54 | @certs_mode = :literal 55 | @certs = { :_ => options[:x509_cert] } 56 | # elsif options[:jwk_uri] # TODO 57 | # @certs_mode = :jwk 58 | # @certs = {} 59 | else 60 | @certs_mode = :old_skool 61 | @certs = {} 62 | end 63 | 64 | @certs_expiry = options.fetch(:expiry, GOOGLE_CERTS_EXPIRY) 65 | end 66 | 67 | ## 68 | # If it validates, returns a hash with the JWT payload from the ID Token. 69 | # You have to provide an "aud" value, which must match the 70 | # token's field with that name, and will similarly check cid if provided. 71 | # 72 | # If something fails, raises an error 73 | # 74 | # @param [String] token 75 | # The string form of the token 76 | # @param [String] aud 77 | # The required audience value 78 | # @param [String] cid 79 | # The optional client-id ("azp" field) value 80 | # 81 | # @return [Hash] The decoded ID token 82 | def check(token, aud, cid = 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 94 | else 95 | raise CertificateError, 'Unable to retrieve Google public keys' 96 | end 97 | end 98 | 99 | payload 100 | end 101 | end 102 | 103 | private 104 | 105 | # tries to validate the token against each cached cert. 106 | # Returns the token payload or raises a ValidationError or 107 | # nil, which means none of the certs validated. 108 | def check_cached_certs(token, aud, cid) 109 | payload = nil 110 | 111 | # find first public key that validates this token 112 | @certs.detect do |key, cert| 113 | begin 114 | public_key = cert.public_key 115 | decoded_token = JWT.decode(token, public_key, !!public_key, { :algorithm => 'RS256' }) 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'] 125 | end 126 | payload 127 | rescue JWT::ExpiredSignature 128 | raise ExpiredTokenError, 'Token signature is expired' 129 | rescue JWT::DecodeError 130 | nil # go on, try the next cert 131 | end 132 | end 133 | 134 | if payload 135 | if !(payload.has_key?('aud') && Array(aud).include?(payload['aud'])) 136 | raise AudienceMismatchError, 'Token audience mismatch' 137 | end 138 | if cid && payload['cid'] != cid 139 | raise ClientIDMismatchError, 'Token client-id mismatch' 140 | end 141 | if !GOOGLE_ISSUERS.include?(payload['iss']) 142 | raise InvalidIssuerError, 'Token issuer mismatch' 143 | end 144 | payload 145 | else 146 | nil 147 | end 148 | end 149 | 150 | # returns false if there was a problem 151 | def refresh_certs 152 | case @certs_mode 153 | when :literal 154 | true # no-op 155 | when :old_skool 156 | old_skool_refresh_certs 157 | # when :jwk # TODO 158 | # jwk_refresh_certs 159 | end 160 | end 161 | 162 | def old_skool_refresh_certs 163 | return true unless certs_cache_expired? 164 | 165 | uri = URI(GOOGLE_CERTS_URI) 166 | get = Net::HTTP::Get.new uri.request_uri 167 | http = Net::HTTP.new(uri.host, uri.port) 168 | http.use_ssl = true 169 | res = http.request(get) 170 | 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] 175 | @certs.merge! new_certs 176 | @certs_last_refresh = Time.now 177 | true 178 | else 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 186 | else 187 | true 188 | end 189 | end 190 | end 191 | end 192 | -------------------------------------------------------------------------------- /lib/google-id-token/version.rb: -------------------------------------------------------------------------------- 1 | module GoogleIDToken 2 | VERSION = "1.4.2".freeze 3 | end 4 | -------------------------------------------------------------------------------- /spec/google-id-token_spec.rb: -------------------------------------------------------------------------------- 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 | # @author Tim Bray, adapted from code by Bob Aman 17 | 18 | require 'spec_helper' 19 | require 'fakeweb' 20 | require 'openssl' 21 | 22 | CERTS_URI = 'https://www.googleapis.com/oauth2/v1/certs' 23 | 24 | describe GoogleIDToken::Validator do 25 | 26 | describe '#check' do 27 | before(:all) do 28 | crypto = generate_certificate 29 | @key = crypto[:key] 30 | @cert = crypto[:cert] 31 | end 32 | 33 | let(:iss) { 'https://accounts.google.com' } 34 | let(:aud) { '123456789.apps.googleusercontent.com' } 35 | let(:cid) { '123456789.apps.googleusercontent.com' } 36 | let(:exp) { Time.now + 10 } 37 | 38 | let(:payload) {{ 39 | exp: exp.to_i, 40 | iss: iss, 41 | aud: aud, 42 | cid: cid, 43 | user_id: '12345', 44 | email: 'test@gmail.com', 45 | provider_id: 'google.com', 46 | verified: true 47 | }} 48 | 49 | let(:token) { JWT.encode(payload, @key, 'RS256') } 50 | 51 | it 'should successfully validate against a passed-in X509 cert' do 52 | literal_validator = GoogleIDToken::Validator.new(x509_cert: @cert) 53 | result = literal_validator.check(token, aud) 54 | expect(result).to_not be_nil 55 | expect(result['aud']).to eq aud 56 | end 57 | 58 | context 'with old_skool certs' do 59 | let(:validator) { GoogleIDToken::Validator.new } 60 | 61 | context 'when unable to fetch old_skool Google certs' do 62 | before do 63 | FakeWeb::register_uri(:get, CERTS_URI, 64 | status: ["404", "Not found"], 65 | body: 'Ouch!') 66 | end 67 | 68 | it 'raises an error' do 69 | expect { 70 | validator.check('whatever', 'whatever') 71 | }.to raise_error(GoogleIDToken::CertificateError) 72 | end 73 | end 74 | 75 | context 'when able to fetch old_skool certs' do 76 | before(:all) do 77 | crypto = generate_certificate 78 | @key2 = crypto[:key] 79 | @cert2 = crypto[:cert] 80 | @certs_body = JSON.dump({ 81 | "123" => @cert.to_pem, 82 | "321" => @cert2.to_pem 83 | }) 84 | end 85 | 86 | before do 87 | FakeWeb::register_uri(:get, CERTS_URI, 88 | status: ["200", "Success"], 89 | body: @certs_body) 90 | end 91 | 92 | it 'successfully validates a good token' do 93 | result = validator.check(token, aud, cid) 94 | expect(result).to_not be_nil 95 | expect(result['aud']).to eq aud 96 | expect(result['cid']).to eq cid 97 | expect(result['azp']).to eq cid 98 | end 99 | 100 | it 'fails to validate a mangled token' do 101 | bad_token = token.gsub('x', 'y') 102 | expect { 103 | validator.check(bad_token, aud, cid) 104 | }.to raise_error(GoogleIDToken::SignatureError) 105 | end 106 | 107 | it 'fails to validate a good token with wrong aud field' do 108 | expect { 109 | validator.check(token, aud + 'x', cid) 110 | }.to raise_error(GoogleIDToken::AudienceMismatchError) 111 | end 112 | 113 | it 'fails to validate a good token with wrong cid field' do 114 | expect { 115 | validator.check(token, aud, cid + 'x') 116 | }.to raise_error(GoogleIDToken::ClientIDMismatchError) 117 | end 118 | 119 | context 'when aud is an array' do 120 | let(:aud_array) { ['123456789.apps.googleusercontent.com', '987654321.apps.googleusercontent.com'] } 121 | 122 | it 'it checks aud against an array' do 123 | expect { 124 | validator.check(token, aud_array, cid) 125 | }.not_to raise_error(GoogleIDToken::AudienceMismatchError) 126 | end 127 | end 128 | 129 | context 'when token is expired' do 130 | let(:exp) { Time.now - 10 } 131 | 132 | it 'fails to validate a good token' do 133 | expect { 134 | validator.check(token, aud, cid) 135 | }.to raise_error(GoogleIDToken::ExpiredTokenError) 136 | end 137 | end 138 | 139 | context 'with an invalid issuer' do 140 | let(:iss) { 'https://accounts.fake.com' } 141 | 142 | it 'fails to validate a good token' do 143 | expect { 144 | validator.check(token, aud, cid) 145 | }.to raise_error(GoogleIDToken::InvalidIssuerError) 146 | end 147 | end 148 | 149 | context 'when certificates are not expired' do 150 | before { validator.instance_variable_set(:@certs_last_refresh, Time.now) } 151 | 152 | it 'fails to validate a good token' do 153 | expect { 154 | validator.check(token, aud, cid) 155 | }.to raise_error(GoogleIDToken::SignatureError) 156 | end 157 | end 158 | 159 | context 'when certificates are expired' do 160 | let(:validator) { GoogleIDToken::Validator.new(expiry: 60) } 161 | before { validator.instance_variable_set(:@certs_last_refresh, Time.now - 120) } 162 | 163 | it 'fails to validate a good token' do 164 | result = validator.check(token, aud, cid) 165 | expect(result).to_not be_nil 166 | expect(result['aud']).to eq aud 167 | end 168 | end 169 | 170 | it 'validates a good token with the new azp instead of cid field' do 171 | payload[:azp] = payload[:cid] 172 | payload[:cid] = nil 173 | result = validator.check(token, aud, cid) 174 | expect(result).to_not be_nil 175 | expect(result['aud']).to eq aud 176 | expect(result['cid']).to eq cid 177 | expect(result['azp']).to eq cid 178 | end 179 | end 180 | end 181 | end 182 | 183 | def generate_certificate 184 | key = OpenSSL::PKey::RSA.new(2048) 185 | public_key = key.public_key 186 | 187 | cert_subject = "/C=BE/O=Test/OU=Test/CN=Test" 188 | 189 | cert = OpenSSL::X509::Certificate.new 190 | cert.subject = cert.issuer = OpenSSL::X509::Name.parse(cert_subject) 191 | cert.not_before = Time.now 192 | cert.not_after = Time.now + 365 * 24 * 60 * 60 193 | cert.public_key = public_key 194 | cert.serial = 0x0 195 | cert.version = 2 196 | 197 | cert.sign key, OpenSSL::Digest::SHA1.new 198 | 199 | { key: key, cert: cert } 200 | end 201 | end 202 | -------------------------------------------------------------------------------- /spec/spec_helper.rb: -------------------------------------------------------------------------------- 1 | $LOAD_PATH.unshift File.expand_path('../../lib', __FILE__) 2 | require 'google-id-token' 3 | --------------------------------------------------------------------------------