blob: dcbb33c1186f8262bbcf99520e3efc4ebf57a2a9 [file] [log] [blame]
Joe Gregorio8b4c1732011-12-06 11:28:29 -05001#!/usr/bin/python2.4
2#
3# Copyright 2010 Google Inc.
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16
17
18"""Oauth2client tests
19
20Unit tests for oauth2client.
21"""
22
23__author__ = 'jcgregorio@google.com (Joe Gregorio)'
24
25import httplib2
26import os
27import sys
28import time
29import unittest
30import urlparse
31
32try:
33 from urlparse import parse_qs
34except ImportError:
35 from cgi import parse_qs
36
Joe Gregorio8b4c1732011-12-06 11:28:29 -050037from apiclient.http import HttpMockSequence
38from oauth2client import crypt
Joe Gregorio549230c2012-01-11 10:38:05 -050039from oauth2client.anyjson import simplejson
Joe Gregorio8b4c1732011-12-06 11:28:29 -050040from oauth2client.client import SignedJwtAssertionCredentials
Joe Gregorio8b4c1732011-12-06 11:28:29 -050041from oauth2client.client import VerifyJwtTokenError
Joe Gregorio549230c2012-01-11 10:38:05 -050042from oauth2client.client import verify_id_token
Joe Gregorio8b4c1732011-12-06 11:28:29 -050043
44
45def datafile(filename):
46 f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'r')
47 data = f.read()
48 f.close()
49 return data
50
51
52class CryptTests(unittest.TestCase):
53
54 def test_sign_and_verify(self):
55 private_key = datafile('privatekey.p12')
56 public_key = datafile('publickey.pem')
57
58 signer = crypt.Signer.from_string(private_key)
59 signature = signer.sign('foo')
60
61 verifier = crypt.Verifier.from_string(public_key, True)
62
63 self.assertTrue(verifier.verify('foo', signature))
64
65 self.assertFalse(verifier.verify('bar', signature))
66 self.assertFalse(verifier.verify('foo', 'bad signagure'))
67
68 def _check_jwt_failure(self, jwt, expected_error):
69 try:
70 public_key = datafile('publickey.pem')
71 certs = {'foo': public_key}
72 audience = 'https://www.googleapis.com/auth/id?client_id=' + \
73 'external_public_key@testing.gserviceaccount.com'
74 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
75 self.fail('Should have thrown for %s' % jwt)
76 except:
77 e = sys.exc_info()[1]
78 msg = e.args[0]
79 self.assertTrue(expected_error in msg)
80
81 def _create_signed_jwt(self):
82 private_key = datafile('privatekey.p12')
83 signer = crypt.Signer.from_string(private_key)
84 audience = 'some_audience_address@testing.gserviceaccount.com'
85 now = long(time.time())
86
87 return crypt.make_signed_jwt(
88 signer,
89 {
90 'aud': audience,
91 'iat': now,
92 'exp': now + 300,
93 'user': 'billy bob',
94 'metadata': {'meta': 'data'},
95 })
96
97 def test_verify_id_token(self):
98 jwt = self._create_signed_jwt()
99 public_key = datafile('publickey.pem')
100 certs = {'foo': public_key }
101 audience = 'some_audience_address@testing.gserviceaccount.com'
102 contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500103 self.assertEqual('billy bob', contents['user'])
104 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500105
106 def test_verify_id_token_with_certs_uri(self):
107 jwt = self._create_signed_jwt()
108
109 http = HttpMockSequence([
110 ({'status': '200'}, datafile('certs.json')),
111 ])
112
113 contents = verify_id_token(jwt,
114 'some_audience_address@testing.gserviceaccount.com', http)
Joe Gregorio654f4a22012-02-09 14:15:44 -0500115 self.assertEqual('billy bob', contents['user'])
116 self.assertEqual('data', contents['metadata']['meta'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500117
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500118 def test_verify_id_token_with_certs_uri_fails(self):
119 jwt = self._create_signed_jwt()
120
121 http = HttpMockSequence([
122 ({'status': '404'}, datafile('certs.json')),
123 ])
124
125 self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
126 'some_audience_address@testing.gserviceaccount.com', http)
127
128 def test_verify_id_token_bad_tokens(self):
129 private_key = datafile('privatekey.p12')
130
131 # Wrong number of segments
132 self._check_jwt_failure('foo', 'Wrong number of segments')
133
134 # Not json
135 self._check_jwt_failure('foo.bar.baz',
136 'Can\'t parse token')
137
138 # Bad signature
139 jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
140 self._check_jwt_failure(jwt, 'Invalid token signature')
141
142 # No expiration
143 signer = crypt.Signer.from_string(private_key)
144 audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
145 'external_public_key@testing.gserviceaccount.com'
146 jwt = crypt.make_signed_jwt(signer, {
147 'aud': 'audience',
148 'iat': time.time(),
149 }
150 )
151 self._check_jwt_failure(jwt, 'No exp field in token')
152
153 # No issued at
154 jwt = crypt.make_signed_jwt(signer, {
155 'aud': 'audience',
156 'exp': time.time() + 400,
157 }
158 )
159 self._check_jwt_failure(jwt, 'No iat field in token')
160
161 # Too early
162 jwt = crypt.make_signed_jwt(signer, {
163 'aud': 'audience',
164 'iat': time.time() + 301,
165 'exp': time.time() + 400,
166 })
167 self._check_jwt_failure(jwt, 'Token used too early')
168
169 # Too late
170 jwt = crypt.make_signed_jwt(signer, {
171 'aud': 'audience',
172 'iat': time.time() - 500,
173 'exp': time.time() - 301,
174 })
175 self._check_jwt_failure(jwt, 'Token used too late')
176
177 # Wrong target
178 jwt = crypt.make_signed_jwt(signer, {
179 'aud': 'somebody else',
180 'iat': time.time(),
181 'exp': time.time() + 300,
182 })
183 self._check_jwt_failure(jwt, 'Wrong recipient')
184
185 def test_signed_jwt_assertion_credentials(self):
186 private_key = datafile('privatekey.p12')
187 credentials = SignedJwtAssertionCredentials(
188 'some_account@example.com',
189 private_key,
190 scope='read+write',
191 prn='joe@example.org')
192 http = HttpMockSequence([
193 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
194 ({'status': '200'}, 'echo_request_headers'),
195 ])
196 http = credentials.authorize(http)
197 resp, content = http.request('http://example.org')
Joe Gregorio654f4a22012-02-09 14:15:44 -0500198 self.assertEqual('Bearer 1/3w', content['Authorization'])
Joe Gregorio8b4c1732011-12-06 11:28:29 -0500199
200if __name__ == '__main__':
201 unittest.main()