From 1b58527b072a66a9e792fcf9389d35b6972bfab8 Mon Sep 17 00:00:00 2001 From: Jon Wayne Parrott Date: Mon, 12 Dec 2016 21:33:45 -0800 Subject: [PATCH] Add crypt.Signer.from_service_account_file --- google/auth/crypt.py | 15 +++++++++++++++ tests/test_crypt.py | 14 ++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/google/auth/crypt.py b/google/auth/crypt.py index d347600f0..8d5ac7c74 100644 --- a/google/auth/crypt.py +++ b/google/auth/crypt.py @@ -227,3 +227,18 @@ def from_string(cls, key, key_id=None): raise ValueError('No key could be detected.') return cls(private_key, key_id=key_id) + + @classmethod + def from_service_account_file(cls, filename): + """Creates a Signer instance from a service account .json file + in Google format. + + Args: + filename (str): The path to the service account .json file. + + Returns: + Signer: The constructed signer. + """ + from google.auth import _service_account_info + _, signer = _service_account_info.from_filename(filename) + return signer diff --git a/tests/test_crypt.py b/tests/test_crypt.py index 33105e414..fd70f4bb8 100644 --- a/tests/test_crypt.py +++ b/tests/test_crypt.py @@ -13,6 +13,7 @@ # limitations under the License. import os +import json import mock from pyasn1_modules import pem @@ -59,6 +60,12 @@ with open(os.path.join(DATA_DIR, 'privatekey.p12'), 'rb') as fh: PKCS12_KEY_BYTES = fh.read() +# The service account JSON file can be generated from the Google Cloud Console. +SERVICE_ACCOUNT_JSON_FILE = os.path.join(DATA_DIR, 'service_account.json') + +with open(SERVICE_ACCOUNT_JSON_FILE, 'r') as fh: + SERVICE_ACCOUNT_INFO = json.load(fh) + def test_verify_signature(): to_sign = b'foo' @@ -191,3 +198,10 @@ def test_from_string_bogus_key(self): key_bytes = 'bogus-key' with pytest.raises(ValueError): crypt.Signer.from_string(key_bytes) + + def test_from_service_account_file(self): + signer = crypt.Signer.from_service_account_file( + SERVICE_ACCOUNT_JSON_FILE) + + assert signer.key_id == SERVICE_ACCOUNT_INFO['private_key_id'] + assert isinstance(signer._key, rsa.key.PrivateKey)