|
| 1 | +# Copyright 2014 Google Inc. All rights reserved. |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +import mock |
| 16 | +import os |
| 17 | +import sys |
| 18 | +import unittest |
| 19 | + |
| 20 | +try: |
| 21 | + reload |
| 22 | +except NameError: |
| 23 | + # For Python3 (though importlib should be used, silly 3.3). |
| 24 | + from imp import reload |
| 25 | + |
| 26 | +from oauth2client.client import HAS_OPENSSL |
| 27 | +from oauth2client.client import SignedJwtAssertionCredentials |
| 28 | +from oauth2client import crypt |
| 29 | + |
| 30 | + |
| 31 | +def datafile(filename): |
| 32 | + f = open(os.path.join(os.path.dirname(__file__), 'data', filename), 'rb') |
| 33 | + data = f.read() |
| 34 | + f.close() |
| 35 | + return data |
| 36 | + |
| 37 | + |
| 38 | +class Test_pkcs12_key_as_pem(unittest.TestCase): |
| 39 | + |
| 40 | + def _make_signed_jwt_creds(self, private_key_file='privatekey.p12', |
| 41 | + private_key=None): |
| 42 | + private_key = private_key or datafile(private_key_file) |
| 43 | + return SignedJwtAssertionCredentials( |
| 44 | + |
| 45 | + private_key, |
| 46 | + scope='read+write', |
| 47 | + |
| 48 | + |
| 49 | + def test_succeeds(self): |
| 50 | + self.assertEqual(True, HAS_OPENSSL) |
| 51 | + |
| 52 | + credentials = self._make_signed_jwt_creds() |
| 53 | + pem_contents = crypt.pkcs12_key_as_pem(credentials.private_key, |
| 54 | + credentials.private_key_password) |
| 55 | + pkcs12_key_as_pem = datafile('pem_from_pkcs12.pem') |
| 56 | + pkcs12_key_as_pem = crypt._parse_pem_key(pkcs12_key_as_pem) |
| 57 | + self.assertEqual(pem_contents, pkcs12_key_as_pem) |
| 58 | + |
| 59 | + def test_without_openssl(self): |
| 60 | + openssl_mod = sys.modules['OpenSSL'] |
| 61 | + try: |
| 62 | + sys.modules['OpenSSL'] = None |
| 63 | + reload(crypt) |
| 64 | + self.assertRaises(NotImplementedError, crypt.pkcs12_key_as_pem, |
| 65 | + 'FOO', 'BAR') |
| 66 | + finally: |
| 67 | + sys.modules['OpenSSL'] = openssl_mod |
| 68 | + reload(crypt) |
| 69 | + |
| 70 | + def test_with_nonsense_key(self): |
| 71 | + credentials = self._make_signed_jwt_creds(private_key=b'NOT_A_KEY') |
| 72 | + self.assertRaises(crypt.crypto.Error, crypt.pkcs12_key_as_pem, |
| 73 | + credentials.private_key, credentials.private_key_password) |
0 commit comments