blob: 50dab5af6984076bc8467551bcd067c09ad121b5 [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)
103 self.assertEquals('billy bob', contents['user'])
104 self.assertEquals('data', contents['metadata']['meta'])
105
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)
115 self.assertEquals('billy bob', contents['user'])
116 self.assertEquals('data', contents['metadata']['meta'])
117
118
119 def test_verify_id_token_with_certs_uri_fails(self):
120 jwt = self._create_signed_jwt()
121
122 http = HttpMockSequence([
123 ({'status': '404'}, datafile('certs.json')),
124 ])
125
126 self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
127 'some_audience_address@testing.gserviceaccount.com', http)
128
129 def test_verify_id_token_bad_tokens(self):
130 private_key = datafile('privatekey.p12')
131
132 # Wrong number of segments
133 self._check_jwt_failure('foo', 'Wrong number of segments')
134
135 # Not json
136 self._check_jwt_failure('foo.bar.baz',
137 'Can\'t parse token')
138
139 # Bad signature
140 jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
141 self._check_jwt_failure(jwt, 'Invalid token signature')
142
143 # No expiration
144 signer = crypt.Signer.from_string(private_key)
145 audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
146 'external_public_key@testing.gserviceaccount.com'
147 jwt = crypt.make_signed_jwt(signer, {
148 'aud': 'audience',
149 'iat': time.time(),
150 }
151 )
152 self._check_jwt_failure(jwt, 'No exp field in token')
153
154 # No issued at
155 jwt = crypt.make_signed_jwt(signer, {
156 'aud': 'audience',
157 'exp': time.time() + 400,
158 }
159 )
160 self._check_jwt_failure(jwt, 'No iat field in token')
161
162 # Too early
163 jwt = crypt.make_signed_jwt(signer, {
164 'aud': 'audience',
165 'iat': time.time() + 301,
166 'exp': time.time() + 400,
167 })
168 self._check_jwt_failure(jwt, 'Token used too early')
169
170 # Too late
171 jwt = crypt.make_signed_jwt(signer, {
172 'aud': 'audience',
173 'iat': time.time() - 500,
174 'exp': time.time() - 301,
175 })
176 self._check_jwt_failure(jwt, 'Token used too late')
177
178 # Wrong target
179 jwt = crypt.make_signed_jwt(signer, {
180 'aud': 'somebody else',
181 'iat': time.time(),
182 'exp': time.time() + 300,
183 })
184 self._check_jwt_failure(jwt, 'Wrong recipient')
185
186 def test_signed_jwt_assertion_credentials(self):
187 private_key = datafile('privatekey.p12')
188 credentials = SignedJwtAssertionCredentials(
189 'some_account@example.com',
190 private_key,
191 scope='read+write',
192 prn='joe@example.org')
193 http = HttpMockSequence([
194 ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
195 ({'status': '200'}, 'echo_request_headers'),
196 ])
197 http = credentials.authorize(http)
198 resp, content = http.request('http://example.org')
199 self.assertEquals(content['authorization'], 'OAuth 1/3w')
200
201if __name__ == '__main__':
202 unittest.main()