1# Copyright 2016 Google LLC
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"""Base classes for cryptographic signers and verifiers."""
16
17import abc
18import io
19import json
20
21import six
22
23
24_JSON_FILE_PRIVATE_KEY = "private_key"
25_JSON_FILE_PRIVATE_KEY_ID = "private_key_id"
26
27
28@six.add_metaclass(abc.ABCMeta)
29class Verifier(object):
30    """Abstract base class for crytographic signature verifiers."""
31
32    @abc.abstractmethod
33    def verify(self, message, signature):
34        """Verifies a message against a cryptographic signature.
35
36        Args:
37            message (Union[str, bytes]): The message to verify.
38            signature (Union[str, bytes]): The cryptography signature to check.
39
40        Returns:
41            bool: True if message was signed by the private key associated
42            with the public key that this object was constructed with.
43        """
44        # pylint: disable=missing-raises-doc,redundant-returns-doc
45        # (pylint doesn't recognize that this is abstract)
46        raise NotImplementedError("Verify must be implemented")
47
48
49@six.add_metaclass(abc.ABCMeta)
50class Signer(object):
51    """Abstract base class for cryptographic signers."""
52
53    @abc.abstractproperty
54    def key_id(self):
55        """Optional[str]: The key ID used to identify this private key."""
56        raise NotImplementedError("Key id must be implemented")
57
58    @abc.abstractmethod
59    def sign(self, message):
60        """Signs a message.
61
62        Args:
63            message (Union[str, bytes]): The message to be signed.
64
65        Returns:
66            bytes: The signature of the message.
67        """
68        # pylint: disable=missing-raises-doc,redundant-returns-doc
69        # (pylint doesn't recognize that this is abstract)
70        raise NotImplementedError("Sign must be implemented")
71
72
73@six.add_metaclass(abc.ABCMeta)
74class FromServiceAccountMixin(object):
75    """Mix-in to enable factory constructors for a Signer."""
76
77    @abc.abstractmethod
78    def from_string(cls, key, key_id=None):
79        """Construct an Signer instance from a private key string.
80
81        Args:
82            key (str): Private key as a string.
83            key_id (str): An optional key id used to identify the private key.
84
85        Returns:
86            google.auth.crypt.Signer: The constructed signer.
87
88        Raises:
89            ValueError: If the key cannot be parsed.
90        """
91        raise NotImplementedError("from_string must be implemented")
92
93    @classmethod
94    def from_service_account_info(cls, info):
95        """Creates a Signer instance instance from a dictionary containing
96        service account info in Google format.
97
98        Args:
99            info (Mapping[str, str]): The service account info in Google
100                format.
101
102        Returns:
103            google.auth.crypt.Signer: The constructed signer.
104
105        Raises:
106            ValueError: If the info is not in the expected format.
107        """
108        if _JSON_FILE_PRIVATE_KEY not in info:
109            raise ValueError(
110                "The private_key field was not found in the service account " "info."
111            )
112
113        return cls.from_string(
114            info[_JSON_FILE_PRIVATE_KEY], info.get(_JSON_FILE_PRIVATE_KEY_ID)
115        )
116
117    @classmethod
118    def from_service_account_file(cls, filename):
119        """Creates a Signer instance from a service account .json file
120        in Google format.
121
122        Args:
123            filename (str): The path to the service account .json file.
124
125        Returns:
126            google.auth.crypt.Signer: The constructed signer.
127        """
128        with io.open(filename, "r", encoding="utf-8") as json_file:
129            data = json.load(json_file)
130
131        return cls.from_service_account_info(data)
132