[mq]: id_token2
diff --git a/Makefile b/Makefile
index 86c0b4e..28c9f26 100644
--- a/Makefile
+++ b/Makefile
@@ -1,8 +1,23 @@
 pep8:
 	find apiclient samples -name "*.py" | xargs pep8 --ignore=E111,E202
 
+APP_ENGINE_PATH=../google_appengine
+
 test:
-	python runtests.py tests
+	python runtests.py tests/test_discovery.py
+	python runtests.py tests/test_errors.py
+	python runtests.py tests/test_http.py
+	python runtests.py tests/test_json_model.py
+	python runtests.py tests/test_mocks.py
+	python runtests.py tests/test_model.py
+	python runtests.py tests/test_oauth2client_clientsecrets.py
+	python runtests.py tests/test_oauth2client_django_orm.py
+	python runtests.py tests/test_oauth2client_file.py
+	python runtests.py tests/test_oauth2client_jwt.py
+	python runtests.py tests/test_oauth2client.py
+	python runtests.py tests/test_oauth.py
+	python runtests.py tests/test_protobuf_model.py
+	python runtests.py tests/test_oauth2client_appengine.py
 
 .PHONY: docs
 docs:
diff --git a/oauth2client/client.py b/oauth2client/client.py
index d77e776..3440c23 100644
--- a/oauth2client/client.py
+++ b/oauth2client/client.py
@@ -19,15 +19,28 @@
 
 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
 
+import base64
 import clientsecrets
 import copy
 import datetime
 import httplib2
 import logging
+import os
 import sys
+import time
 import urllib
 import urlparse
 
+
+HAS_OPENSSL = False
+try:
+  from oauth2client.crypt import Signer
+  from oauth2client.crypt import make_signed_jwt
+  from oauth2client.crypt import verify_signed_jwt_with_certs
+  HAS_OPENSSL = True
+except ImportError:
+  pass
+
 try:  # pragma: no cover
   import simplejson
 except ImportError:  # pragma: no cover
@@ -43,10 +56,21 @@
 except ImportError:
   from cgi import parse_qsl
 
+# Determine if we can write to the file system, and if we can use a local file
+# cache behing httplib2.
+if hasattr(os, 'tempnam'):
+  # Put cache file in the director '.cache'.
+  CACHED_HTTP = httplib2.Http('.cache')
+else:
+  CACHED_HTTP = httplib2.Http()
+
 logger = logging.getLogger(__name__)
 
 # Expiry is stored in RFC3339 UTC format
-EXPIRY_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
+EXPIRY_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
+
+# Which certs to use to validate id_tokens received.
+ID_TOKEN_VERIFICATON_CERTS = 'https://www.googleapis.com/oauth2/v1/certs'
 
 
 class Error(Exception):
@@ -73,6 +97,11 @@
   pass
 
 
+class VerifyJwtTokenError(Error):
+  """Could on retrieve certificates for validation."""
+  pass
+
+
 def _abstract():
   raise NotImplementedError('You need to override this function')
 
@@ -229,14 +258,13 @@
   """Credentials object for OAuth 2.0.
 
   Credentials can be applied to an httplib2.Http object using the authorize()
-  method, which then signs each request from that object with the OAuth 2.0
-  access token.
+  method, which then adds the OAuth 2.0 access token to each request.
 
   OAuth2Credentials objects may be safely pickled and unpickled.
   """
 
   def __init__(self, access_token, client_id, client_secret, refresh_token,
-               token_expiry, token_uri, user_agent):
+               token_expiry, token_uri, user_agent, id_token=None):
     """Create an instance of OAuth2Credentials.
 
     This constructor is not usually called by the user, instead
@@ -250,9 +278,10 @@
       token_expiry: datetime, when the access_token expires.
       token_uri: string, URI of token endpoint.
       user_agent: string, The HTTP User-Agent to provide for this application.
+      id_token: object, The identity of the resource owner.
 
     Notes:
-      store: callable, a callable that when passed a Credential
+      store: callable, A callable that when passed a Credential
         will store the credential back to where it came from.
         This is needed to store the latest access_token if it
         has expired and been refreshed.
@@ -265,6 +294,7 @@
     self.token_expiry = token_expiry
     self.token_uri = token_uri
     self.user_agent = user_agent
+    self.id_token = id_token
 
     # True if the credentials have been revoked or expired and can't be
     # refreshed.
@@ -299,7 +329,8 @@
         data['refresh_token'],
         data['token_expiry'],
         data['token_uri'],
-        data['user_agent'])
+        data['user_agent'],
+        data.get('id_token', None))
     retval.invalid = data['invalid']
     return retval
 
@@ -607,6 +638,145 @@
     """
     _abstract()
 
+if HAS_OPENSSL:
+  # PyOpenSSL is not a prerequisite for oauth2client, so if it is missing then
+  # don't create the SignedJwtAssertionCredentials or the verify_id_token()
+  # method.
+
+  class SignedJwtAssertionCredentials(AssertionCredentials):
+    """Credentials object used for OAuth 2.0 Signed JWT assertion grants.
+
+    This credential does not require a flow to instantiate because it
+    represents a two legged flow, and therefore has all of the required
+    information to generate and refresh its own access tokens.
+    """
+
+    MAX_TOKEN_LIFETIME_SECS = 3600 # 1 hour in seconds
+
+    def __init__(self,
+        service_account_name,
+        private_key,
+        scope,
+        private_key_password='notasecret',
+        user_agent=None,
+        token_uri='https://accounts.google.com/o/oauth2/token',
+        **kwargs):
+      """Constructor for SignedJwtAssertionCredentials.
+
+      Args:
+        service_account_name: string, id for account, usually an email address.
+        private_key: string, private key in P12 format.
+        scope: string or list of strings, scope(s) of the credentials being
+          requested.
+        private_key_password: string, password for private_key.
+        user_agent: string, HTTP User-Agent to provide for this application.
+        token_uri: string, URI for token endpoint. For convenience
+          defaults to Google's endpoints but any OAuth 2.0 provider can be used.
+        kwargs: kwargs, Additional parameters to add to the JWT token, for
+          example prn=joe@xample.org."""
+
+      super(SignedJwtAssertionCredentials, self).__init__(
+          'http://oauth.net/grant_type/jwt/1.0/bearer',
+          user_agent,
+          token_uri=token_uri,
+          )
+
+      if type(scope) is list:
+        scope = ' '.join(scope)
+      self.scope = scope
+
+      self.private_key = private_key
+      self.private_key_password = private_key_password
+      self.service_account_name = service_account_name
+      self.kwargs = kwargs
+
+    @classmethod
+    def from_json(cls, s):
+      data = simplejson.loads(s)
+      retval = SignedJwtAssertionCredentials(
+          data['service_account_name'],
+          data['private_key'],
+          data['private_key_password'],
+          data['scope'],
+          data['user_agent'],
+          data['token_uri'],
+          data['kwargs']
+          )
+      retval.invalid = data['invalid']
+      return retval
+
+    def _generate_assertion(self):
+      """Generate the assertion that will be used in the request."""
+      now = long(time.time())
+      payload = {
+          'aud': self.token_uri,
+          'scope': self.scope,
+          'iat': now,
+          'exp': now + SignedJwtAssertionCredentials.MAX_TOKEN_LIFETIME_SECS,
+          'iss': self.service_account_name
+      }
+      payload.update(self.kwargs)
+      logging.debug(str(payload))
+
+      return make_signed_jwt(
+          Signer.from_string(self.private_key, self.private_key_password),
+          payload)
+
+
+  def verify_id_token(id_token, audience, http=None,
+      cert_uri=ID_TOKEN_VERIFICATON_CERTS):
+    """Verifies a signed JWT id_token.
+
+    Args:
+      id_token: string, A Signed JWT.
+      audience: string, The audience 'aud' that the token should be for.
+      http: httplib2.Http, instance to use to make the HTTP request. Callers
+        should supply an instance that has caching enabled.
+      cert_uri: string, URI of the certificates in JSON format to
+        verify the JWT against.
+
+    Returns:
+      The deserialized JSON in the JWT.
+
+    Raises:
+      oauth2client.crypt.AppIdentityError if the JWT fails to verify.
+    """
+    if http is None:
+      http = CACHED_HTTP
+
+    resp, content = http.request(cert_uri)
+
+    if resp.status == 200:
+      certs = simplejson.loads(content)
+      return verify_signed_jwt_with_certs(id_token, certs, audience)
+    else:
+      raise VerifyJwtTokenError('Status code: %d' % resp.status)
+
+
+def _urlsafe_b64decode(b64string):
+  padded = b64string + '=' * (4 - len(b64string) % 4)
+  return base64.urlsafe_b64decode(padded)
+
+
+def _extract_id_token(id_token):
+  """Extract the JSON payload from a JWT.
+
+  Does the extraction w/o checking the signature.
+
+  Args:
+    id_token: string, OAuth 2.0 id_token.
+
+  Returns:
+    object, The deserialized JSON payload.
+  """
+  segments = id_token.split('.')
+
+  if (len(segments) != 3):
+    raise VerifyJwtTokenError(
+      'Wrong number of segments in token: %s' % id_token)
+
+  return simplejson.loads(_urlsafe_b64decode(segments[1]))
+
 
 class OAuth2WebServerFlow(Flow):
   """Does the Web Server Flow for OAuth 2.0.
@@ -704,6 +874,7 @@
 
     if http is None:
       http = httplib2.Http()
+
     resp, content = http.request(self.token_uri, method='POST', body=body,
                                  headers=headers)
     if resp.status == 200:
@@ -716,10 +887,14 @@
         token_expiry = datetime.datetime.utcnow() + datetime.timedelta(
             seconds=int(d['expires_in']))
 
+      if 'id_token' in d:
+        d['id_token'] = _extract_id_token(d['id_token'])
+
       logger.info('Successfully retrieved access token: %s' % content)
       return OAuth2Credentials(access_token, self.client_id,
                                self.client_secret, refresh_token, token_expiry,
-                               self.token_uri, self.user_agent)
+                               self.token_uri, self.user_agent,
+                               id_token=d.get('id_token', None))
     else:
       logger.error('Failed to retrieve access token: %s' % content)
       error_msg = 'Invalid response %s.' % resp['status']
diff --git a/oauth2client/crypt.py b/oauth2client/crypt.py
new file mode 100644
index 0000000..523c921
--- /dev/null
+++ b/oauth2client/crypt.py
@@ -0,0 +1,251 @@
+#!/usr/bin/python2.4
+# -*- coding: utf-8 -*-
+#
+# Copyright (C) 2011 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import base64
+import hashlib
+import logging
+import time
+
+from OpenSSL import crypto
+
+try:  # pragma: no cover
+  import simplejson
+except ImportError:  # pragma: no cover
+  try:
+    # Try to import from django, should work on App Engine
+    from django.utils import simplejson
+  except ImportError:
+    # Should work for Python2.6 and higher.
+    import json as simplejson
+
+
+CLOCK_SKEW_SECS = 300  # 5 minutes in seconds
+AUTH_TOKEN_LIFETIME_SECS = 300  # 5 minutes in seconds
+MAX_TOKEN_LIFETIME_SECS = 86400  # 1 day in seconds
+
+
+class AppIdentityError(Exception):
+  pass
+
+
+class Verifier(object):
+  """Verifies the signature on a message."""
+
+  def __init__(self, pubkey):
+    """Constructor.
+
+    Args:
+      pubkey, OpenSSL.crypto.PKey, The public key to verify with.
+    """
+    self._pubkey = pubkey
+
+  def verify(self, message, signature):
+    """Verifies a message against a signature.
+
+    Args:
+      message: string, The message to verify.
+      signature: string, The signature on the message.
+
+    Returns:
+      True if message was singed by the private key associated with the public
+      key that this object was constructed with.
+    """
+    try:
+      crypto.verify(self._pubkey, signature, message, 'sha256')
+      return True
+    except:
+      return False
+
+  @staticmethod
+  def from_string(key_pem, is_x509_cert):
+    """Construct a Verified instance from a string.
+
+    Args:
+      key_pem: string, public key in PEM format.
+      is_x509_cert: bool, True if key_pem is an X509 cert, otherwise it is
+        expected to be an RSA key in PEM format.
+
+    Returns:
+      Verifier instance.
+
+    Raises:
+      OpenSSL.crypto.Error if the key_pem can't be parsed.
+    """
+    if is_x509_cert:
+      pubkey = crypto.load_certificate(crypto.FILETYPE_PEM, key_pem)
+    else:
+      pubkey = crypto.load_privatekey(crypto.FILETYPE_PEM, key_pem)
+    return Verifier(pubkey)
+
+
+class Signer(object):
+  """Signs messages with a private key."""
+
+  def __init__(self, pkey):
+    """Constructor.
+
+    Args:
+      pkey, OpenSSL.crypto.PKey, The private key to sign with.
+    """
+    self._key = pkey
+
+  def sign(self, message):
+    """Signs a message.
+
+    Args:
+      message: string, Message to be signed.
+
+    Returns:
+      string, The signature of the message for the given key.
+    """
+    return crypto.sign(self._key, message, 'sha256')
+
+  @staticmethod
+  def from_string(key, password='notasecret'):
+    """Construct a Signer instance from a string.
+
+    Args:
+      key: string, private key in P12 format.
+      password: string, password for the private key file.
+
+    Returns:
+      Signer instance.
+
+    Raises:
+      OpenSSL.crypto.Error if the key can't be parsed.
+    """
+    pkey = crypto.load_pkcs12(key, password).get_privatekey()
+    return Signer(pkey)
+
+
+def _urlsafe_b64encode(raw_bytes):
+  return base64.urlsafe_b64encode(raw_bytes).rstrip('=')
+
+
+def _urlsafe_b64decode(b64string):
+  padded = b64string + '=' * (4 - len(b64string) % 4)
+  return base64.urlsafe_b64decode(padded)
+
+
+def _json_encode(data):
+  return simplejson.dumps(data, separators = (',', ':'))
+
+
+def make_signed_jwt(signer, payload):
+  """Make a signed JWT.
+
+  See http://self-issued.info/docs/draft-jones-json-web-token.html.
+
+  Args:
+    signer: crypt.Signer, Cryptographic signer.
+    payload: dict, Dictionary of data to convert to JSON and then sign.
+
+  Returns:
+    string, The JWT for the payload.
+  """
+  header = {'typ': 'JWT', 'alg': 'RS256'}
+
+  segments = [
+          _urlsafe_b64encode(_json_encode(header)),
+          _urlsafe_b64encode(_json_encode(payload)),
+  ]
+  signing_input = '.'.join(segments)
+
+  signature = signer.sign(signing_input)
+  segments.append(_urlsafe_b64encode(signature))
+
+  logging.debug(str(segments))
+
+  return '.'.join(segments)
+
+
+def verify_signed_jwt_with_certs(jwt, certs, audience):
+  """Verify a JWT against public certs.
+
+  See http://self-issued.info/docs/draft-jones-json-web-token.html.
+
+  Args:
+    jwt: string, A JWT.
+    certs: dict, Dictionary where values of public keys in PEM format.
+    audience: string, The audience, 'aud', that this JWT should contain. If
+      None then the JWT's 'aud' parameter is not verified.
+
+  Returns:
+    dict, The deserialized JSON payload in the JWT.
+
+  Raises:
+    AppIdentityError if any checks are failed.
+  """
+  segments = jwt.split('.')
+
+  if (len(segments) != 3):
+    raise AppIdentityError(
+      'Wrong number of segments in token: %s' % jwt)
+  signed = '%s.%s' % (segments[0], segments[1])
+
+  signature = _urlsafe_b64decode(segments[2])
+
+  # Parse token.
+  json_body = _urlsafe_b64decode(segments[1])
+  try:
+    parsed = simplejson.loads(json_body)
+  except:
+    raise AppIdentityError('Can\'t parse token: %s' % json_body)
+
+  # Check signature.
+  verified = False
+  for (keyname, pem) in certs.items():
+    verifier = Verifier.from_string(pem, True)
+    if (verifier.verify(signed, signature)):
+      verified = True
+      break
+  if not verified:
+    raise AppIdentityError('Invalid token signature: %s' % jwt)
+
+  # Check creation timestamp.
+  iat = parsed.get('iat')
+  if iat is None:
+    raise AppIdentityError('No iat field in token: %s' % json_body)
+  earliest = iat - CLOCK_SKEW_SECS
+
+  # Check expiration timestamp.
+  now = long(time.time())
+  exp = parsed.get('exp')
+  if exp is None:
+    raise AppIdentityError('No exp field in token: %s' % json_body)
+  if exp >= now + MAX_TOKEN_LIFETIME_SECS:
+    raise AppIdentityError(
+      'exp field too far in future: %s' % json_body)
+  latest = exp + CLOCK_SKEW_SECS
+
+  if now < earliest:
+    raise AppIdentityError('Token used too early, %d < %d: %s' %
+      (now, earliest, json_body))
+  if now > latest:
+    raise AppIdentityError('Token used too late, %d > %d: %s' %
+      (now, latest, json_body))
+
+  # Check audience.
+  if audience is not None:
+    aud = parsed.get('aud')
+    if aud is None:
+      raise AppIdentityError('No aud field in token: %s' % json_body)
+    if aud != audience:
+      raise AppIdentityError('Wrong recipient, %s != %s: %s' %
+          (aud, audience, json_body))
+
+  return parsed
diff --git a/runtests.py b/runtests.py
index c1f9d1d..8ec0f54 100644
--- a/runtests.py
+++ b/runtests.py
@@ -1,5 +1,6 @@
 #!/usr/bin/env python
 import glob
+import imp
 import logging
 import os
 import sys
@@ -23,63 +24,11 @@
 use_library('django', '1.2')
 
 
-def build_suite(folder, verbosity):
-  # find all of the test modules
-  top_level_modules = map(fullmodname, glob.glob(os.path.join(folder, 'test_*.py')))
-  # TODO(ade) Verify that this works on Windows. If it doesn't then switch to os.walk instead
-  lower_level_modules = map(fullmodname, glob.glob(os.path.join(folder, '*/test_*.py')))
-  modules = top_level_modules + lower_level_modules
-  if verbosity > 0:
-    print "Running the tests found in the following modules:"
-    print modules
-
-  # load all of the tests into a suite
-  try:
-    return unittest.TestLoader().loadTestsFromNames(modules)
-  except Exception, exception:
-    # attempt to produce a more specific message
-    for module in modules:
-      __import__(module)
-    raise
-
-def run(test_folder_name, verbosity, exit_on_failure):
-  # Build and run the tests in test_folder_name
-  tests = build_suite(test_folder_name, verbosity)
-  result = unittest.TextTestRunner(verbosity=verbosity).run(tests)
-  if exit_on_failure and not result.wasSuccessful():
-    sys.exit(1)
-  cleanup()
-
 def main():
-  if '--help' in sys.argv:
-    print 'Usage: python runtests.py [-q|--quiet|-v|--verbose] [--exit_on_failure] [tests|functional_tests|contrib_tests]'
-    return
-  verbosity = 1
-  exit_on_failure = '--exit_on_failure' in sys.argv
-  if '-q' in sys.argv or '--quiet' in sys.argv:
-    verbosity = 0
-  if "-v" in sys.argv or '--verbose' in sys.argv:
-    verbosity = 2
-  if verbosity == 0:
-    logging.disable(logging.CRITICAL)
-  elif verbosity == 1:
-    logging.disable(logging.ERROR)
-  elif verbosity == 2:
-    logging.basicConfig(level=logging.DEBUG)
+  module = imp.load_source('test', sys.argv[1])
+  test = unittest.TestLoader().loadTestsFromModule(module)
+  result = unittest.TextTestRunner(verbosity=1).run(test)
 
-  import dev_appserver
-  dev_appserver.fix_sys_path()
-  # Allow user to run a specific folder of tests
-  if 'tests' in sys.argv:
-    run('tests', verbosity, exit_on_failure)
-  elif 'functional_tests' in sys.argv:
-    run('functional_tests', verbosity, exit_on_failure)
-  elif 'contrib_tests' in sys.argv:
-    run('contrib_tests', verbosity, exit_on_failure)
-  else:
-    run('tests', verbosity, exit_on_failure)
-    run('functional_tests', verbosity, exit_on_failure)
-    run('contrib_tests', verbosity, exit_on_failure)
 
 if __name__ == '__main__':
   main()
diff --git a/samples/plus/client_secrets.json b/samples/plus/client_secrets.json
index a232f37..18d9ea8 100644
--- a/samples/plus/client_secrets.json
+++ b/samples/plus/client_secrets.json
@@ -1,7 +1,7 @@
 {
   "web": {
-    "client_id": "[[INSERT CLIENT ID HERE]]",
-    "client_secret": "[[INSERT CLIENT SECRET HERE]]",
+    "client_id": "887851474342-kd6d83gonj4dorjbahqg1bf94jjpe10p.apps.googleusercontent.com",
+    "client_secret": "vkGqFqTBSSOI9jX69B8G2xww",
     "redirect_uris": [],
     "auth_uri": "https://accounts.google.com/o/oauth2/auth",
     "token_uri": "https://accounts.google.com/o/oauth2/token"
diff --git a/tests/data/certs.json b/tests/data/certs.json
new file mode 100644
index 0000000..fa09416
--- /dev/null
+++ b/tests/data/certs.json
@@ -0,0 +1,3 @@
+{
+"foo": "-----BEGIN CERTIFICATE-----\r\nMIIDIzCCAgugAwIBAgIJAMfISuBQ5m+5MA0GCSqGSIb3DQEBBQUAMBUxEzARBgNV\r\nBAMTCnVuaXQtdGVzdHMwHhcNMTExMjA2MTYyNjAyWhcNMjExMjAzMTYyNjAyWjAV\r\nMRMwEQYDVQQDEwp1bml0LXRlc3RzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB\r\nCgKCAQEA4ej0p7bQ7L/r4rVGUz9RN4VQWoej1Bg1mYWIDYslvKrk1gpj7wZgkdmM\r\n7oVK2OfgrSj/FCTkInKPqaCR0gD7K80q+mLBrN3PUkDrJQZpvRZIff3/xmVU1Wer\r\nuQLFJjnFb2dqu0s/FY/2kWiJtBCakXvXEOb7zfbINuayL+MSsCGSdVYsSliS5qQp\r\ngyDap+8b5fpXZVJkq92hrcNtbkg7hCYUJczt8n9hcCTJCfUpApvaFQ18pe+zpyl4\r\n+WzkP66I28hniMQyUlA1hBiskT7qiouq0m8IOodhv2fagSZKjOTTU2xkSBc//fy3\r\nZpsL7WqgsZS7Q+0VRK8gKfqkxg5OYQIDAQABo3YwdDAdBgNVHQ4EFgQU2RQ8yO+O\r\ngN8oVW2SW7RLrfYd9jEwRQYDVR0jBD4wPIAU2RQ8yO+OgN8oVW2SW7RLrfYd9jGh\r\nGaQXMBUxEzARBgNVBAMTCnVuaXQtdGVzdHOCCQDHyErgUOZvuTAMBgNVHRMEBTAD\r\nAQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBRv+M/6+FiVu7KXNjFI5pSN17OcW5QUtPr\r\nodJMlWrJBtynn/TA1oJlYu3yV5clc/71Vr/AxuX5xGP+IXL32YDF9lTUJXG/uUGk\r\n+JETpKmQviPbRsvzYhz4pf6ZIOZMc3/GIcNq92ECbseGO+yAgyWUVKMmZM0HqXC9\r\novNslqe0M8C1sLm1zAR5z/h/litE7/8O2ietija3Q/qtl2TOXJdCA6sgjJX2WUql\r\nybrC55ct18NKf3qhpcEkGQvFU40rVYApJpi98DiZPYFdx1oBDp/f4uZ3ojpxRVFT\r\ncDwcJLfNRCPUhormsY7fDS9xSyThiHsW9mjJYdcaKQkwYZ0F11yB\r\n-----END CERTIFICATE-----\r\n"
+}
diff --git a/tests/data/create-private-keys.sh b/tests/data/create-private-keys.sh
new file mode 100644
index 0000000..b21cbdb
--- /dev/null
+++ b/tests/data/create-private-keys.sh
@@ -0,0 +1,9 @@
+#!/bin/bash
+
+openssl req -new -newkey rsa:2048 -days 3650 -nodes -x509 \
+  -keyout privatekey.pem -out publickey.pem \
+  -subj "/CN=unit-tests"
+
+openssl pkcs12 -export -out privatekey.p12 \
+  -inkey privatekey.pem -in publickey.pem \
+  -name "key" -passout pass:notasecret
diff --git a/tests/data/privatekey.p12 b/tests/data/privatekey.p12
new file mode 100644
index 0000000..c369ecb
--- /dev/null
+++ b/tests/data/privatekey.p12
Binary files differ
diff --git a/tests/data/privatekey.pem b/tests/data/privatekey.pem
new file mode 100644
index 0000000..5744354
--- /dev/null
+++ b/tests/data/privatekey.pem
@@ -0,0 +1,27 @@
+-----BEGIN RSA PRIVATE KEY-----
+MIIEpAIBAAKCAQEA4ej0p7bQ7L/r4rVGUz9RN4VQWoej1Bg1mYWIDYslvKrk1gpj
+7wZgkdmM7oVK2OfgrSj/FCTkInKPqaCR0gD7K80q+mLBrN3PUkDrJQZpvRZIff3/
+xmVU1WeruQLFJjnFb2dqu0s/FY/2kWiJtBCakXvXEOb7zfbINuayL+MSsCGSdVYs
+SliS5qQpgyDap+8b5fpXZVJkq92hrcNtbkg7hCYUJczt8n9hcCTJCfUpApvaFQ18
+pe+zpyl4+WzkP66I28hniMQyUlA1hBiskT7qiouq0m8IOodhv2fagSZKjOTTU2xk
+SBc//fy3ZpsL7WqgsZS7Q+0VRK8gKfqkxg5OYQIDAQABAoIBAQDGGHzQxGKX+ANk
+nQi53v/c6632dJKYXVJC+PDAz4+bzU800Y+n/bOYsWf/kCp94XcG4Lgsdd0Gx+Zq
+HD9CI1IcqqBRR2AFscsmmX6YzPLTuEKBGMW8twaYy3utlFxElMwoUEsrSWRcCA1y
+nHSDzTt871c7nxCXHxuZ6Nm/XCL7Bg8uidRTSC1sQrQyKgTPhtQdYrPQ4WZ1A4J9
+IisyDYmZodSNZe5P+LTJ6M1SCgH8KH9ZGIxv3diMwzNNpk3kxJc9yCnja4mjiGE2
+YCNusSycU5IhZwVeCTlhQGcNeV/skfg64xkiJE34c2y2ttFbdwBTPixStGaF09nU
+Z422D40BAoGBAPvVyRRsC3BF+qZdaSMFwI1yiXY7vQw5+JZh01tD28NuYdRFzjcJ
+vzT2n8LFpj5ZfZFvSMLMVEFVMgQvWnN0O6xdXvGov6qlRUSGaH9u+TCPNnIldjMP
+B8+xTwFMqI7uQr54wBB+Poq7dVRP+0oHb0NYAwUBXoEuvYo3c/nDoRcZAoGBAOWl
+aLHjMv4CJbArzT8sPfic/8waSiLV9Ixs3Re5YREUTtnLq7LoymqB57UXJB3BNz/2
+eCueuW71avlWlRtE/wXASj5jx6y5mIrlV4nZbVuyYff0QlcG+fgb6pcJQuO9DxMI
+aqFGrWP3zye+LK87a6iR76dS9vRU+bHZpSVvGMKJAoGAFGt3TIKeQtJJyqeUWNSk
+klORNdcOMymYMIlqG+JatXQD1rR6ThgqOt8sgRyJqFCVT++YFMOAqXOBBLnaObZZ
+CFbh1fJ66BlSjoXff0W+SuOx5HuJJAa5+WtFHrPajwxeuRcNa8jwxUsB7n41wADu
+UqWWSRedVBg4Ijbw3nWwYDECgYB0pLew4z4bVuvdt+HgnJA9n0EuYowVdadpTEJg
+soBjNHV4msLzdNqbjrAqgz6M/n8Ztg8D2PNHMNDNJPVHjJwcR7duSTA6w2p/4k28
+bvvk/45Ta3XmzlxZcZSOct3O31Cw0i2XDVc018IY5be8qendDYM08icNo7vQYkRH
+504kQQKBgQDjx60zpz8ozvm1XAj0wVhi7GwXe+5lTxiLi9Fxq721WDxPMiHDW2XL
+YXfFVy/9/GIMvEiGYdmarK1NW+VhWl1DC5xhDg0kvMfxplt4tynoq1uTsQTY31Mx
+BeF5CT/JuNYk3bEBF0H/Q3VGO1/ggVS+YezdFbLWIRoMnLj6XCFEGg==
+-----END RSA PRIVATE KEY-----
diff --git a/tests/data/publickey.pem b/tests/data/publickey.pem
new file mode 100644
index 0000000..7af6ca3
--- /dev/null
+++ b/tests/data/publickey.pem
@@ -0,0 +1,19 @@
+-----BEGIN CERTIFICATE-----
+MIIDIzCCAgugAwIBAgIJAMfISuBQ5m+5MA0GCSqGSIb3DQEBBQUAMBUxEzARBgNV
+BAMTCnVuaXQtdGVzdHMwHhcNMTExMjA2MTYyNjAyWhcNMjExMjAzMTYyNjAyWjAV
+MRMwEQYDVQQDEwp1bml0LXRlc3RzMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
+CgKCAQEA4ej0p7bQ7L/r4rVGUz9RN4VQWoej1Bg1mYWIDYslvKrk1gpj7wZgkdmM
+7oVK2OfgrSj/FCTkInKPqaCR0gD7K80q+mLBrN3PUkDrJQZpvRZIff3/xmVU1Wer
+uQLFJjnFb2dqu0s/FY/2kWiJtBCakXvXEOb7zfbINuayL+MSsCGSdVYsSliS5qQp
+gyDap+8b5fpXZVJkq92hrcNtbkg7hCYUJczt8n9hcCTJCfUpApvaFQ18pe+zpyl4
++WzkP66I28hniMQyUlA1hBiskT7qiouq0m8IOodhv2fagSZKjOTTU2xkSBc//fy3
+ZpsL7WqgsZS7Q+0VRK8gKfqkxg5OYQIDAQABo3YwdDAdBgNVHQ4EFgQU2RQ8yO+O
+gN8oVW2SW7RLrfYd9jEwRQYDVR0jBD4wPIAU2RQ8yO+OgN8oVW2SW7RLrfYd9jGh
+GaQXMBUxEzARBgNVBAMTCnVuaXQtdGVzdHOCCQDHyErgUOZvuTAMBgNVHRMEBTAD
+AQH/MA0GCSqGSIb3DQEBBQUAA4IBAQBRv+M/6+FiVu7KXNjFI5pSN17OcW5QUtPr
+odJMlWrJBtynn/TA1oJlYu3yV5clc/71Vr/AxuX5xGP+IXL32YDF9lTUJXG/uUGk
++JETpKmQviPbRsvzYhz4pf6ZIOZMc3/GIcNq92ECbseGO+yAgyWUVKMmZM0HqXC9
+ovNslqe0M8C1sLm1zAR5z/h/litE7/8O2ietija3Q/qtl2TOXJdCA6sgjJX2WUql
+ybrC55ct18NKf3qhpcEkGQvFU40rVYApJpi98DiZPYFdx1oBDp/f4uZ3ojpxRVFT
+cDwcJLfNRCPUhormsY7fDS9xSyThiHsW9mjJYdcaKQkwYZ0F11yB
+-----END CERTIFICATE-----
diff --git a/tests/test_oauth2client.py b/tests/test_oauth2client.py
index a23d1da..9acc9cf 100644
--- a/tests/test_oauth2client.py
+++ b/tests/test_oauth2client.py
@@ -22,6 +22,7 @@
 
 __author__ = 'jcgregorio@google.com (Joe Gregorio)'
 
+import base64
 import datetime
 import httplib2
 import unittest
@@ -50,6 +51,8 @@
 from oauth2client.client import FlowExchangeError
 from oauth2client.client import OAuth2Credentials
 from oauth2client.client import OAuth2WebServerFlow
+from oauth2client.client import VerifyJwtTokenError
+from oauth2client.client import _extract_id_token
 
 
 class OAuth2CredentialsTests(unittest.TestCase):
@@ -143,6 +146,7 @@
     resp, content = http.request('http://example.com')
     self.assertEqual(content['authorization'], 'OAuth foo')
 
+
 class TestAssertionCredentials(unittest.TestCase):
   assertion_text = "This is the assertion"
   assertion_type = "http://www.google.com/assertionType"
@@ -172,6 +176,24 @@
     self.assertEqual(content['authorization'], 'OAuth 1/3w')
 
 
+class ExtractIdTokenText(unittest.TestCase):
+  """Tests _extract_id_token()."""
+
+  def test_extract_success(self):
+    body = {'foo': 'bar'}
+    payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
+    jwt = 'stuff.' + payload + '.signature'
+
+    extracted = _extract_id_token(jwt)
+    self.assertEqual(body, extracted)
+
+  def test_extract_failure(self):
+    body = {'foo': 'bar'}
+    payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
+    jwt = 'stuff.' + payload
+
+    self.assertRaises(VerifyJwtTokenError, _extract_id_token, jwt)
+
 class OAuth2WebServerFlowTest(unittest.TestCase):
 
   def setUp(self):
@@ -245,6 +267,30 @@
     credentials = self.flow.step2_exchange('some random code', http)
     self.assertEqual(credentials.token_expiry, None)
 
+  def test_exchange_id_token_fail(self):
+    http = HttpMockSequence([
+      ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
+       "refresh_token":"8xLOxBtZp8",
+       "id_token": "stuff.payload"}"""),
+      ])
+
+    self.assertRaises(VerifyJwtTokenError, self.flow.step2_exchange,
+      'some random code', http)
+
+  def test_exchange_id_token_fail(self):
+    body = {'foo': 'bar'}
+    payload = base64.urlsafe_b64encode(simplejson.dumps(body)).strip('=')
+    jwt = 'stuff.' + payload + '.signature'
+
+    http = HttpMockSequence([
+      ({'status': '200'}, """{ "access_token":"SlAV32hkKG",
+       "refresh_token":"8xLOxBtZp8",
+       "id_token": "%s"}""" % jwt),
+      ])
+
+    credentials = self.flow.step2_exchange('some random code', http)
+    self.assertEquals(body, credentials.id_token)
+
 
 if __name__ == '__main__':
   unittest.main()
diff --git a/tests/test_oauth2client_appengine.py b/tests/test_oauth2client_appengine.py
index 8d8064c..ca9d940 100644
--- a/tests/test_oauth2client_appengine.py
+++ b/tests/test_oauth2client_appengine.py
@@ -32,6 +32,9 @@
 except ImportError:
     from cgi import parse_qs
 
+import dev_appserver
+dev_appserver.fix_sys_path()
+
 from apiclient.anyjson import simplejson
 from apiclient.http import HttpMockSequence
 from google.appengine.api import apiproxy_stub
diff --git a/tests/test_oauth2client_django_orm.py b/tests/test_oauth2client_django_orm.py
index 67ec314..dbd2e20 100644
--- a/tests/test_oauth2client_django_orm.py
+++ b/tests/test_oauth2client_django_orm.py
@@ -73,3 +73,7 @@
   def test_field_pickled(self):
     prep_value = self.field.get_db_prep_value(self.flow, connection=None)
     self.assertEqual(prep_value, self.pickle)
+
+
+if __name__ == '__main__':
+  unittest.main()
diff --git a/tests/test_oauth2client_jwt.py b/tests/test_oauth2client_jwt.py
new file mode 100644
index 0000000..01a7331
--- /dev/null
+++ b/tests/test_oauth2client_jwt.py
@@ -0,0 +1,211 @@
+#!/usr/bin/python2.4
+#
+# Copyright 2010 Google Inc.
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+#      http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+
+"""Oauth2client tests
+
+Unit tests for oauth2client.
+"""
+
+__author__ = 'jcgregorio@google.com (Joe Gregorio)'
+
+import httplib2
+import os
+import sys
+import time
+import unittest
+import urlparse
+
+try:
+    from urlparse import parse_qs
+except ImportError:
+    from cgi import parse_qs
+
+try:  # pragma: no cover
+  import simplejson
+except ImportError:  # pragma: no cover
+  try:
+    # Try to import from django, should work on App Engine
+    from django.utils import simplejson
+  except ImportError:
+    # Should work for Python2.6 and higher.
+    import json as simplejson
+
+from apiclient.http import HttpMockSequence
+from oauth2client import crypt
+from oauth2client.client import SignedJwtAssertionCredentials
+from oauth2client.client import verify_id_token
+from oauth2client.client import VerifyJwtTokenError
+
+
+def datafile(filename):
+  f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'r')
+  data = f.read()
+  f.close()
+  return data
+
+
+class CryptTests(unittest.TestCase):
+
+  def test_sign_and_verify(self):
+    private_key = datafile('privatekey.p12')
+    public_key = datafile('publickey.pem')
+
+    signer = crypt.Signer.from_string(private_key)
+    signature = signer.sign('foo')
+
+    verifier = crypt.Verifier.from_string(public_key, True)
+
+    self.assertTrue(verifier.verify('foo', signature))
+
+    self.assertFalse(verifier.verify('bar', signature))
+    self.assertFalse(verifier.verify('foo', 'bad signagure'))
+
+  def _check_jwt_failure(self, jwt, expected_error):
+      try:
+          public_key = datafile('publickey.pem')
+          certs = {'foo': public_key}
+          audience = 'https://www.googleapis.com/auth/id?client_id=' + \
+              'external_public_key@testing.gserviceaccount.com'
+          contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
+          self.fail('Should have thrown for %s' % jwt)
+      except:
+          e = sys.exc_info()[1]
+          msg = e.args[0]
+          self.assertTrue(expected_error in msg)
+
+  def _create_signed_jwt(self):
+    private_key = datafile('privatekey.p12')
+    signer = crypt.Signer.from_string(private_key)
+    audience = 'some_audience_address@testing.gserviceaccount.com'
+    now = long(time.time())
+
+    return crypt.make_signed_jwt(
+        signer,
+        {
+        'aud': audience,
+        'iat': now,
+        'exp': now + 300,
+        'user': 'billy bob',
+        'metadata': {'meta': 'data'},
+        })
+
+  def test_verify_id_token(self):
+    jwt = self._create_signed_jwt()
+    public_key = datafile('publickey.pem')
+    certs = {'foo': public_key }
+    audience = 'some_audience_address@testing.gserviceaccount.com'
+    contents = crypt.verify_signed_jwt_with_certs(jwt, certs, audience)
+    self.assertEquals('billy bob', contents['user'])
+    self.assertEquals('data', contents['metadata']['meta'])
+
+  def test_verify_id_token_with_certs_uri(self):
+    jwt = self._create_signed_jwt()
+
+    http = HttpMockSequence([
+      ({'status': '200'}, datafile('certs.json')),
+      ])
+
+    contents = verify_id_token(jwt,
+        'some_audience_address@testing.gserviceaccount.com', http)
+    self.assertEquals('billy bob', contents['user'])
+    self.assertEquals('data', contents['metadata']['meta'])
+
+
+  def test_verify_id_token_with_certs_uri_fails(self):
+    jwt = self._create_signed_jwt()
+
+    http = HttpMockSequence([
+      ({'status': '404'}, datafile('certs.json')),
+      ])
+
+    self.assertRaises(VerifyJwtTokenError, verify_id_token, jwt,
+        'some_audience_address@testing.gserviceaccount.com', http)
+
+  def test_verify_id_token_bad_tokens(self):
+    private_key = datafile('privatekey.p12')
+
+    # Wrong number of segments
+    self._check_jwt_failure('foo', 'Wrong number of segments')
+
+    # Not json
+    self._check_jwt_failure('foo.bar.baz',
+        'Can\'t parse token')
+
+    # Bad signature
+    jwt = 'foo.%s.baz' % crypt._urlsafe_b64encode('{"a":"b"}')
+    self._check_jwt_failure(jwt, 'Invalid token signature')
+
+    # No expiration
+    signer = crypt.Signer.from_string(private_key)
+    audience = 'https:#www.googleapis.com/auth/id?client_id=' + \
+        'external_public_key@testing.gserviceaccount.com'
+    jwt = crypt.make_signed_jwt(signer, {
+          'aud': 'audience',
+          'iat': time.time(),
+          }
+        )
+    self._check_jwt_failure(jwt, 'No exp field in token')
+
+    # No issued at
+    jwt = crypt.make_signed_jwt(signer, {
+          'aud': 'audience',
+          'exp': time.time() + 400,
+        }
+      )
+    self._check_jwt_failure(jwt, 'No iat field in token')
+
+    # Too early
+    jwt = crypt.make_signed_jwt(signer, {
+        'aud': 'audience',
+        'iat': time.time() + 301,
+        'exp': time.time() + 400,
+    })
+    self._check_jwt_failure(jwt, 'Token used too early')
+
+    # Too late
+    jwt = crypt.make_signed_jwt(signer, {
+        'aud': 'audience',
+        'iat': time.time() - 500,
+        'exp': time.time() - 301,
+    })
+    self._check_jwt_failure(jwt, 'Token used too late')
+
+    # Wrong target
+    jwt = crypt.make_signed_jwt(signer, {
+        'aud': 'somebody else',
+        'iat': time.time(),
+        'exp': time.time() + 300,
+    })
+    self._check_jwt_failure(jwt, 'Wrong recipient')
+
+  def test_signed_jwt_assertion_credentials(self):
+    private_key = datafile('privatekey.p12')
+    credentials = SignedJwtAssertionCredentials(
+        'some_account@example.com',
+        private_key,
+        scope='read+write',
+        prn='joe@example.org')
+    http = HttpMockSequence([
+      ({'status': '200'}, '{"access_token":"1/3w","expires_in":3600}'),
+      ({'status': '200'}, 'echo_request_headers'),
+      ])
+    http = credentials.authorize(http)
+    resp, content = http.request('http://example.org')
+    self.assertEquals(content['authorization'], 'OAuth 1/3w')
+
+if __name__ == '__main__':
+  unittest.main()