We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Implement service_account.Credentials.to_jwt_credentials()
(Context: #29)


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `google/oauth2/service_account.py`
Content:
```
1 # Copyright 2016 Google Inc.
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 """Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0
16 
17 This module implements the JWT Profile for OAuth 2.0 Authorization Grants
18 as defined by `RFC 7523`_ with particular support for how this RFC is
19 implemented in Google's infrastructure. Google refers to these credentials
20 as *Service Accounts*.
21 
22 Service accounts are used for server-to-server communication, such as
23 interactions between a web application server and a Google service. The
24 service account belongs to your application instead of to an individual end
25 user. In contrast to other OAuth 2.0 profiles, no users are involved and your
26 application "acts" as the service account.
27 
28 Typically an application uses a service account when the application uses
29 Google APIs to work with its own data rather than a user's data. For example,
30 an application that uses Google Cloud Datastore for data persistence would use
31 a service account to authenticate its calls to the Google Cloud Datastore API.
32 However, an application that needs to access a user's Drive documents would
33 use the normal OAuth 2.0 profile.
34 
35 Additionally, Google Apps domain administrators can grant service accounts
36 `domain-wide delegation`_ authority to access user data on behalf of users in
37 the domain.
38 
39 This profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used
40 in place of the usual authorization token returned during the standard
41 OAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as
42 the acquired access token is used as the bearer token when making requests
43 using these credentials.
44 
45 This profile differs from normal OAuth 2.0 profile because no user consent
46 step is required. The use of the private key allows this profile to assert
47 identity directly.
48 
49 This profile also differs from the :mod:`google.auth.jwt` authentication
50 because the JWT credentials use the JWT directly as the bearer token. This
51 profile instead only uses the JWT to obtain an OAuth 2.0 access token. The
52 obtained OAuth 2.0 access token is used as the bearer token.
53 
54 Domain-wide delegation
55 ----------------------
56 
57 Domain-wide delegation allows a service account to access user data on
58 behalf of any user in a Google Apps domain without consent from the user.
59 For example, an application that uses the Google Calendar API to add events to
60 the calendars of all users in a Google Apps domain would use a service account
61 to access the Google Calendar API on behalf of users.
62 
63 The Google Apps administrator must explicitly authorize the service account to
64 do this. This authorization step is referred to as "delegating domain-wide
65 authority" to a service account.
66 
67 You can use domain-wise delegation by creating a set of credentials with a
68 specific subject using :meth:`~Credentials.with_subject`.
69 
70 .. _RFC 7523: https://tools.ietf.org/html/rfc7523
71 """
72 
73 import datetime
74 
75 from google.auth import _helpers
76 from google.auth import _service_account_info
77 from google.auth import credentials
78 from google.auth import jwt
79 from google.oauth2 import _client
80 
81 _DEFAULT_TOKEN_LIFETIME_SECS = 3600  # 1 hour in sections
82 
83 
84 class Credentials(credentials.Signing,
85                   credentials.Scoped,
86                   credentials.Credentials):
87     """Service account credentials
88 
89     Usually, you'll create these credentials with one of the helper
90     constructors. To create credentials using a Google service account
91     private key JSON file::
92 
93         credentials = service_account.Credentials.from_service_account_file(
94             'service-account.json')
95 
96     Or if you already have the service account file loaded::
97 
98         service_account_info = json.load(open('service_account.json'))
99         credentials = service_account.Credentials.from_service_account_info(
100             service_account_info)
101 
102     Both helper methods pass on arguments to the constructor, so you can
103     specify additional scopes and a subject if necessary::
104 
105         credentials = service_account.Credentials.from_service_account_file(
106             'service-account.json',
107             scopes=['email'],
108             subject='user@example.com')
109 
110     The credentials are considered immutable. If you want to modify the scopes
111     or the subject used for delegation, use :meth:`with_scopes` or
112     :meth:`with_subject`::
113 
114         scoped_credentials = credentials.with_scopes(['email'])
115         delegated_credentials = credentials.with_subject(subject)
116     """
117 
118     def __init__(self, signer, service_account_email, token_uri, scopes=None,
119                  subject=None, additional_claims=None):
120         """
121         Args:
122             signer (google.auth.crypt.Signer): The signer used to sign JWTs.
123             service_account_email (str): The service account's email.
124             scopes (Sequence[str]): Scopes to request during the authorization
125                 grant.
126             token_uri (str): The OAuth 2.0 Token URI.
127             subject (str): For domain-wide delegation, the email address of the
128                 user to for which to request delegated access.
129             additional_claims (Mapping[str, str]): Any additional claims for
130                 the JWT assertion used in the authorization grant.
131 
132         .. note:: Typically one of the helper constructors
133             :meth:`from_service_account_file` or
134             :meth:`from_service_account_info` are used instead of calling the
135             constructor directly.
136         """
137         super(Credentials, self).__init__()
138 
139         self._scopes = scopes
140         self._signer = signer
141         self._service_account_email = service_account_email
142         self._subject = subject
143         self._token_uri = token_uri
144 
145         if additional_claims is not None:
146             self._additional_claims = additional_claims
147         else:
148             self._additional_claims = {}
149 
150     @classmethod
151     def _from_signer_and_info(cls, signer, info, **kwargs):
152         """Creates a Credentials instance from a signer and service account
153         info.
154 
155         Args:
156             signer (google.auth.crypt.Signer): The signer used to sign JWTs.
157             info (Mapping[str, str]): The service account info.
158             kwargs: Additional arguments to pass to the constructor.
159 
160         Returns:
161             google.auth.jwt.Credentials: The constructed credentials.
162 
163         Raises:
164             ValueError: If the info is not in the expected format.
165         """
166         return cls(
167             signer,
168             service_account_email=info['client_email'],
169             token_uri=info['token_uri'], **kwargs)
170 
171     @classmethod
172     def from_service_account_info(cls, info, **kwargs):
173         """Creates a Credentials instance from parsed service account info.
174 
175         Args:
176             info (Mapping[str, str]): The service account info in Google
177                 format.
178             kwargs: Additional arguments to pass to the constructor.
179 
180         Returns:
181             google.auth.service_account.Credentials: The constructed
182                 credentials.
183 
184         Raises:
185             ValueError: If the info is not in the expected format.
186         """
187         signer = _service_account_info.from_dict(
188             info, require=['client_email', 'token_uri'])
189         return cls._from_signer_and_info(signer, info, **kwargs)
190 
191     @classmethod
192     def from_service_account_file(cls, filename, **kwargs):
193         """Creates a Credentials instance from a service account json file.
194 
195         Args:
196             filename (str): The path to the service account json file.
197             kwargs: Additional arguments to pass to the constructor.
198 
199         Returns:
200             google.auth.service_account.Credentials: The constructed
201                 credentials.
202         """
203         info, signer = _service_account_info.from_filename(
204             filename, require=['client_email', 'token_uri'])
205         return cls._from_signer_and_info(signer, info, **kwargs)
206 
207     @property
208     def requires_scopes(self):
209         """Checks if the credentials requires scopes.
210 
211         Returns:
212             bool: True if there are no scopes set otherwise False.
213         """
214         return True if not self._scopes else False
215 
216     @_helpers.copy_docstring(credentials.Scoped)
217     def with_scopes(self, scopes):
218         return Credentials(
219             self._signer,
220             service_account_email=self._service_account_email,
221             scopes=scopes,
222             token_uri=self._token_uri,
223             subject=self._subject,
224             additional_claims=self._additional_claims.copy())
225 
226     def with_subject(self, subject):
227         """Create a copy of these credentials with the specified subject.
228 
229         Args:
230             subject (str): The subject claim.
231 
232         Returns:
233             google.auth.service_account.Credentials: A new credentials
234                 instance.
235         """
236         return Credentials(
237             self._signer,
238             service_account_email=self._service_account_email,
239             scopes=self._scopes,
240             token_uri=self._token_uri,
241             subject=subject,
242             additional_claims=self._additional_claims.copy())
243 
244     def _make_authorization_grant_assertion(self):
245         """Create the OAuth 2.0 assertion.
246 
247         This assertion is used during the OAuth 2.0 grant to acquire an
248         access token.
249 
250         Returns:
251             bytes: The authorization grant assertion.
252         """
253         now = _helpers.utcnow()
254         lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)
255         expiry = now + lifetime
256 
257         payload = {
258             'iat': _helpers.datetime_to_secs(now),
259             'exp': _helpers.datetime_to_secs(expiry),
260             # The issuer must be the service account email.
261             'iss': self._service_account_email,
262             # The audience must be the auth token endpoint's URI
263             'aud': self._token_uri,
264             'scope': _helpers.scopes_to_string(self._scopes or ())
265         }
266 
267         payload.update(self._additional_claims)
268 
269         # The subject can be a user email for domain-wide delegation.
270         if self._subject:
271             payload.setdefault('sub', self._subject)
272 
273         token = jwt.encode(self._signer, payload)
274 
275         return token
276 
277     @_helpers.copy_docstring(credentials.Credentials)
278     def refresh(self, request):
279         assertion = self._make_authorization_grant_assertion()
280         access_token, expiry, _ = _client.jwt_grant(
281             request, self._token_uri, assertion)
282         self.token = access_token
283         self.expiry = expiry
284 
285     @_helpers.copy_docstring(credentials.Signing)
286     def sign_bytes(self, message):
287         return self._signer.sign(message)
288
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/google/oauth2/service_account.py b/google/oauth2/service_account.py
--- a/google/oauth2/service_account.py
+++ b/google/oauth2/service_account.py
@@ -204,6 +204,33 @@
             filename, require=['client_email', 'token_uri'])
         return cls._from_signer_and_info(signer, info, **kwargs)
 
+    def to_jwt_credentials(self):
+        """Creates a :cls:`google.auth.jwt.Credentials` instance from this
+        instance.
+
+        The new instance will use the same private key as this instance and
+        will use this instance's service account email as the issuer and
+        subject.
+
+        This is the same as calling
+        :meth:`jwt.Credentials.from_service_account_file` with the same
+        file used to create these credentials::
+
+            svc_creds = service_account.Credentials.from_service_account_file(
+                'service_account.json')
+            jwt_from_svc = svc_credentials.to_jwt_credentials()
+            # is the same as:
+            jwt_creds = jwt.Credentials.from_service_account_file(
+                'service_account.json')
+
+        Returns:
+            google.auth.jwt.Credentials: A new Credentials instance.
+        """
+        return jwt.Credentials(
+            self._signer,
+            issuer=self._service_account_email,
+            subject=self._service_account_email)
+
     @property
     def requires_scopes(self):
         """Checks if the credentials requires scopes.

{"golden_diff": "diff --git a/google/oauth2/service_account.py b/google/oauth2/service_account.py\n--- a/google/oauth2/service_account.py\n+++ b/google/oauth2/service_account.py\n@@ -204,6 +204,33 @@\n             filename, require=['client_email', 'token_uri'])\n         return cls._from_signer_and_info(signer, info, **kwargs)\n \n+    def to_jwt_credentials(self):\n+        \"\"\"Creates a :cls:`google.auth.jwt.Credentials` instance from this\n+        instance.\n+\n+        The new instance will use the same private key as this instance and\n+        will use this instance's service account email as the issuer and\n+        subject.\n+\n+        This is the same as calling\n+        :meth:`jwt.Credentials.from_service_account_file` with the same\n+        file used to create these credentials::\n+\n+            svc_creds = service_account.Credentials.from_service_account_file(\n+                'service_account.json')\n+            jwt_from_svc = svc_credentials.to_jwt_credentials()\n+            # is the same as:\n+            jwt_creds = jwt.Credentials.from_service_account_file(\n+                'service_account.json')\n+\n+        Returns:\n+            google.auth.jwt.Credentials: A new Credentials instance.\n+        \"\"\"\n+        return jwt.Credentials(\n+            self._signer,\n+            issuer=self._service_account_email,\n+            subject=self._service_account_email)\n+\n     @property\n     def requires_scopes(self):\n         \"\"\"Checks if the credentials requires scopes.\n", "issue": "Implement service_account.Credentials.to_jwt_credentials()\n(Context: #29)\n\n", "before_files": [{"content": "# Copyright 2016 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0\n\nThis module implements the JWT Profile for OAuth 2.0 Authorization Grants\nas defined by `RFC 7523`_ with particular support for how this RFC is\nimplemented in Google's infrastructure. Google refers to these credentials\nas *Service Accounts*.\n\nService accounts are used for server-to-server communication, such as\ninteractions between a web application server and a Google service. The\nservice account belongs to your application instead of to an individual end\nuser. In contrast to other OAuth 2.0 profiles, no users are involved and your\napplication \"acts\" as the service account.\n\nTypically an application uses a service account when the application uses\nGoogle APIs to work with its own data rather than a user's data. For example,\nan application that uses Google Cloud Datastore for data persistence would use\na service account to authenticate its calls to the Google Cloud Datastore API.\nHowever, an application that needs to access a user's Drive documents would\nuse the normal OAuth 2.0 profile.\n\nAdditionally, Google Apps domain administrators can grant service accounts\n`domain-wide delegation`_ authority to access user data on behalf of users in\nthe domain.\n\nThis profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used\nin place of the usual authorization token returned during the standard\nOAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as\nthe acquired access token is used as the bearer token when making requests\nusing these credentials.\n\nThis profile differs from normal OAuth 2.0 profile because no user consent\nstep is required. The use of the private key allows this profile to assert\nidentity directly.\n\nThis profile also differs from the :mod:`google.auth.jwt` authentication\nbecause the JWT credentials use the JWT directly as the bearer token. This\nprofile instead only uses the JWT to obtain an OAuth 2.0 access token. The\nobtained OAuth 2.0 access token is used as the bearer token.\n\nDomain-wide delegation\n----------------------\n\nDomain-wide delegation allows a service account to access user data on\nbehalf of any user in a Google Apps domain without consent from the user.\nFor example, an application that uses the Google Calendar API to add events to\nthe calendars of all users in a Google Apps domain would use a service account\nto access the Google Calendar API on behalf of users.\n\nThe Google Apps administrator must explicitly authorize the service account to\ndo this. This authorization step is referred to as \"delegating domain-wide\nauthority\" to a service account.\n\nYou can use domain-wise delegation by creating a set of credentials with a\nspecific subject using :meth:`~Credentials.with_subject`.\n\n.. _RFC 7523: https://tools.ietf.org/html/rfc7523\n\"\"\"\n\nimport datetime\n\nfrom google.auth import _helpers\nfrom google.auth import _service_account_info\nfrom google.auth import credentials\nfrom google.auth import jwt\nfrom google.oauth2 import _client\n\n_DEFAULT_TOKEN_LIFETIME_SECS = 3600  # 1 hour in sections\n\n\nclass Credentials(credentials.Signing,\n                  credentials.Scoped,\n                  credentials.Credentials):\n    \"\"\"Service account credentials\n\n    Usually, you'll create these credentials with one of the helper\n    constructors. To create credentials using a Google service account\n    private key JSON file::\n\n        credentials = service_account.Credentials.from_service_account_file(\n            'service-account.json')\n\n    Or if you already have the service account file loaded::\n\n        service_account_info = json.load(open('service_account.json'))\n        credentials = service_account.Credentials.from_service_account_info(\n            service_account_info)\n\n    Both helper methods pass on arguments to the constructor, so you can\n    specify additional scopes and a subject if necessary::\n\n        credentials = service_account.Credentials.from_service_account_file(\n            'service-account.json',\n            scopes=['email'],\n            subject='user@example.com')\n\n    The credentials are considered immutable. If you want to modify the scopes\n    or the subject used for delegation, use :meth:`with_scopes` or\n    :meth:`with_subject`::\n\n        scoped_credentials = credentials.with_scopes(['email'])\n        delegated_credentials = credentials.with_subject(subject)\n    \"\"\"\n\n    def __init__(self, signer, service_account_email, token_uri, scopes=None,\n                 subject=None, additional_claims=None):\n        \"\"\"\n        Args:\n            signer (google.auth.crypt.Signer): The signer used to sign JWTs.\n            service_account_email (str): The service account's email.\n            scopes (Sequence[str]): Scopes to request during the authorization\n                grant.\n            token_uri (str): The OAuth 2.0 Token URI.\n            subject (str): For domain-wide delegation, the email address of the\n                user to for which to request delegated access.\n            additional_claims (Mapping[str, str]): Any additional claims for\n                the JWT assertion used in the authorization grant.\n\n        .. note:: Typically one of the helper constructors\n            :meth:`from_service_account_file` or\n            :meth:`from_service_account_info` are used instead of calling the\n            constructor directly.\n        \"\"\"\n        super(Credentials, self).__init__()\n\n        self._scopes = scopes\n        self._signer = signer\n        self._service_account_email = service_account_email\n        self._subject = subject\n        self._token_uri = token_uri\n\n        if additional_claims is not None:\n            self._additional_claims = additional_claims\n        else:\n            self._additional_claims = {}\n\n    @classmethod\n    def _from_signer_and_info(cls, signer, info, **kwargs):\n        \"\"\"Creates a Credentials instance from a signer and service account\n        info.\n\n        Args:\n            signer (google.auth.crypt.Signer): The signer used to sign JWTs.\n            info (Mapping[str, str]): The service account info.\n            kwargs: Additional arguments to pass to the constructor.\n\n        Returns:\n            google.auth.jwt.Credentials: The constructed credentials.\n\n        Raises:\n            ValueError: If the info is not in the expected format.\n        \"\"\"\n        return cls(\n            signer,\n            service_account_email=info['client_email'],\n            token_uri=info['token_uri'], **kwargs)\n\n    @classmethod\n    def from_service_account_info(cls, info, **kwargs):\n        \"\"\"Creates a Credentials instance from parsed service account info.\n\n        Args:\n            info (Mapping[str, str]): The service account info in Google\n                format.\n            kwargs: Additional arguments to pass to the constructor.\n\n        Returns:\n            google.auth.service_account.Credentials: The constructed\n                credentials.\n\n        Raises:\n            ValueError: If the info is not in the expected format.\n        \"\"\"\n        signer = _service_account_info.from_dict(\n            info, require=['client_email', 'token_uri'])\n        return cls._from_signer_and_info(signer, info, **kwargs)\n\n    @classmethod\n    def from_service_account_file(cls, filename, **kwargs):\n        \"\"\"Creates a Credentials instance from a service account json file.\n\n        Args:\n            filename (str): The path to the service account json file.\n            kwargs: Additional arguments to pass to the constructor.\n\n        Returns:\n            google.auth.service_account.Credentials: The constructed\n                credentials.\n        \"\"\"\n        info, signer = _service_account_info.from_filename(\n            filename, require=['client_email', 'token_uri'])\n        return cls._from_signer_and_info(signer, info, **kwargs)\n\n    @property\n    def requires_scopes(self):\n        \"\"\"Checks if the credentials requires scopes.\n\n        Returns:\n            bool: True if there are no scopes set otherwise False.\n        \"\"\"\n        return True if not self._scopes else False\n\n    @_helpers.copy_docstring(credentials.Scoped)\n    def with_scopes(self, scopes):\n        return Credentials(\n            self._signer,\n            service_account_email=self._service_account_email,\n            scopes=scopes,\n            token_uri=self._token_uri,\n            subject=self._subject,\n            additional_claims=self._additional_claims.copy())\n\n    def with_subject(self, subject):\n        \"\"\"Create a copy of these credentials with the specified subject.\n\n        Args:\n            subject (str): The subject claim.\n\n        Returns:\n            google.auth.service_account.Credentials: A new credentials\n                instance.\n        \"\"\"\n        return Credentials(\n            self._signer,\n            service_account_email=self._service_account_email,\n            scopes=self._scopes,\n            token_uri=self._token_uri,\n            subject=subject,\n            additional_claims=self._additional_claims.copy())\n\n    def _make_authorization_grant_assertion(self):\n        \"\"\"Create the OAuth 2.0 assertion.\n\n        This assertion is used during the OAuth 2.0 grant to acquire an\n        access token.\n\n        Returns:\n            bytes: The authorization grant assertion.\n        \"\"\"\n        now = _helpers.utcnow()\n        lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)\n        expiry = now + lifetime\n\n        payload = {\n            'iat': _helpers.datetime_to_secs(now),\n            'exp': _helpers.datetime_to_secs(expiry),\n            # The issuer must be the service account email.\n            'iss': self._service_account_email,\n            # The audience must be the auth token endpoint's URI\n            'aud': self._token_uri,\n            'scope': _helpers.scopes_to_string(self._scopes or ())\n        }\n\n        payload.update(self._additional_claims)\n\n        # The subject can be a user email for domain-wide delegation.\n        if self._subject:\n            payload.setdefault('sub', self._subject)\n\n        token = jwt.encode(self._signer, payload)\n\n        return token\n\n    @_helpers.copy_docstring(credentials.Credentials)\n    def refresh(self, request):\n        assertion = self._make_authorization_grant_assertion()\n        access_token, expiry, _ = _client.jwt_grant(\n            request, self._token_uri, assertion)\n        self.token = access_token\n        self.expiry = expiry\n\n    @_helpers.copy_docstring(credentials.Signing)\n    def sign_bytes(self, message):\n        return self._signer.sign(message)\n", "path": "google/oauth2/service_account.py"}], "after_files": [{"content": "# Copyright 2016 Google Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n#      http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\n\"\"\"Service Accounts: JSON Web Token (JWT) Profile for OAuth 2.0\n\nThis module implements the JWT Profile for OAuth 2.0 Authorization Grants\nas defined by `RFC 7523`_ with particular support for how this RFC is\nimplemented in Google's infrastructure. Google refers to these credentials\nas *Service Accounts*.\n\nService accounts are used for server-to-server communication, such as\ninteractions between a web application server and a Google service. The\nservice account belongs to your application instead of to an individual end\nuser. In contrast to other OAuth 2.0 profiles, no users are involved and your\napplication \"acts\" as the service account.\n\nTypically an application uses a service account when the application uses\nGoogle APIs to work with its own data rather than a user's data. For example,\nan application that uses Google Cloud Datastore for data persistence would use\na service account to authenticate its calls to the Google Cloud Datastore API.\nHowever, an application that needs to access a user's Drive documents would\nuse the normal OAuth 2.0 profile.\n\nAdditionally, Google Apps domain administrators can grant service accounts\n`domain-wide delegation`_ authority to access user data on behalf of users in\nthe domain.\n\nThis profile uses a JWT to acquire an OAuth 2.0 access token. The JWT is used\nin place of the usual authorization token returned during the standard\nOAuth 2.0 Authorization Code grant. The JWT is only used for this purpose, as\nthe acquired access token is used as the bearer token when making requests\nusing these credentials.\n\nThis profile differs from normal OAuth 2.0 profile because no user consent\nstep is required. The use of the private key allows this profile to assert\nidentity directly.\n\nThis profile also differs from the :mod:`google.auth.jwt` authentication\nbecause the JWT credentials use the JWT directly as the bearer token. This\nprofile instead only uses the JWT to obtain an OAuth 2.0 access token. The\nobtained OAuth 2.0 access token is used as the bearer token.\n\nDomain-wide delegation\n----------------------\n\nDomain-wide delegation allows a service account to access user data on\nbehalf of any user in a Google Apps domain without consent from the user.\nFor example, an application that uses the Google Calendar API to add events to\nthe calendars of all users in a Google Apps domain would use a service account\nto access the Google Calendar API on behalf of users.\n\nThe Google Apps administrator must explicitly authorize the service account to\ndo this. This authorization step is referred to as \"delegating domain-wide\nauthority\" to a service account.\n\nYou can use domain-wise delegation by creating a set of credentials with a\nspecific subject using :meth:`~Credentials.with_subject`.\n\n.. _RFC 7523: https://tools.ietf.org/html/rfc7523\n\"\"\"\n\nimport datetime\n\nfrom google.auth import _helpers\nfrom google.auth import _service_account_info\nfrom google.auth import credentials\nfrom google.auth import jwt\nfrom google.oauth2 import _client\n\n_DEFAULT_TOKEN_LIFETIME_SECS = 3600  # 1 hour in sections\n\n\nclass Credentials(credentials.Signing,\n                  credentials.Scoped,\n                  credentials.Credentials):\n    \"\"\"Service account credentials\n\n    Usually, you'll create these credentials with one of the helper\n    constructors. To create credentials using a Google service account\n    private key JSON file::\n\n        credentials = service_account.Credentials.from_service_account_file(\n            'service-account.json')\n\n    Or if you already have the service account file loaded::\n\n        service_account_info = json.load(open('service_account.json'))\n        credentials = service_account.Credentials.from_service_account_info(\n            service_account_info)\n\n    Both helper methods pass on arguments to the constructor, so you can\n    specify additional scopes and a subject if necessary::\n\n        credentials = service_account.Credentials.from_service_account_file(\n            'service-account.json',\n            scopes=['email'],\n            subject='user@example.com')\n\n    The credentials are considered immutable. If you want to modify the scopes\n    or the subject used for delegation, use :meth:`with_scopes` or\n    :meth:`with_subject`::\n\n        scoped_credentials = credentials.with_scopes(['email'])\n        delegated_credentials = credentials.with_subject(subject)\n    \"\"\"\n\n    def __init__(self, signer, service_account_email, token_uri, scopes=None,\n                 subject=None, additional_claims=None):\n        \"\"\"\n        Args:\n            signer (google.auth.crypt.Signer): The signer used to sign JWTs.\n            service_account_email (str): The service account's email.\n            scopes (Sequence[str]): Scopes to request during the authorization\n                grant.\n            token_uri (str): The OAuth 2.0 Token URI.\n            subject (str): For domain-wide delegation, the email address of the\n                user to for which to request delegated access.\n            additional_claims (Mapping[str, str]): Any additional claims for\n                the JWT assertion used in the authorization grant.\n\n        .. note:: Typically one of the helper constructors\n            :meth:`from_service_account_file` or\n            :meth:`from_service_account_info` are used instead of calling the\n            constructor directly.\n        \"\"\"\n        super(Credentials, self).__init__()\n\n        self._scopes = scopes\n        self._signer = signer\n        self._service_account_email = service_account_email\n        self._subject = subject\n        self._token_uri = token_uri\n\n        if additional_claims is not None:\n            self._additional_claims = additional_claims\n        else:\n            self._additional_claims = {}\n\n    @classmethod\n    def _from_signer_and_info(cls, signer, info, **kwargs):\n        \"\"\"Creates a Credentials instance from a signer and service account\n        info.\n\n        Args:\n            signer (google.auth.crypt.Signer): The signer used to sign JWTs.\n            info (Mapping[str, str]): The service account info.\n            kwargs: Additional arguments to pass to the constructor.\n\n        Returns:\n            google.auth.jwt.Credentials: The constructed credentials.\n\n        Raises:\n            ValueError: If the info is not in the expected format.\n        \"\"\"\n        return cls(\n            signer,\n            service_account_email=info['client_email'],\n            token_uri=info['token_uri'], **kwargs)\n\n    @classmethod\n    def from_service_account_info(cls, info, **kwargs):\n        \"\"\"Creates a Credentials instance from parsed service account info.\n\n        Args:\n            info (Mapping[str, str]): The service account info in Google\n                format.\n            kwargs: Additional arguments to pass to the constructor.\n\n        Returns:\n            google.auth.service_account.Credentials: The constructed\n                credentials.\n\n        Raises:\n            ValueError: If the info is not in the expected format.\n        \"\"\"\n        signer = _service_account_info.from_dict(\n            info, require=['client_email', 'token_uri'])\n        return cls._from_signer_and_info(signer, info, **kwargs)\n\n    @classmethod\n    def from_service_account_file(cls, filename, **kwargs):\n        \"\"\"Creates a Credentials instance from a service account json file.\n\n        Args:\n            filename (str): The path to the service account json file.\n            kwargs: Additional arguments to pass to the constructor.\n\n        Returns:\n            google.auth.service_account.Credentials: The constructed\n                credentials.\n        \"\"\"\n        info, signer = _service_account_info.from_filename(\n            filename, require=['client_email', 'token_uri'])\n        return cls._from_signer_and_info(signer, info, **kwargs)\n\n    def to_jwt_credentials(self):\n        \"\"\"Creates a :cls:`google.auth.jwt.Credentials` instance from this\n        instance.\n\n        The new instance will use the same private key as this instance and\n        will use this instance's service account email as the issuer and\n        subject.\n\n        This is the same as calling\n        :meth:`jwt.Credentials.from_service_account_file` with the same\n        file used to create these credentials::\n\n            svc_creds = service_account.Credentials.from_service_account_file(\n                'service_account.json')\n            jwt_from_svc = svc_credentials.to_jwt_credentials()\n            # is the same as:\n            jwt_creds = jwt.Credentials.from_service_account_file(\n                'service_account.json')\n\n        Returns:\n            google.auth.jwt.Credentials: A new Credentials instance.\n        \"\"\"\n        return jwt.Credentials(\n            self._signer,\n            issuer=self._service_account_email,\n            subject=self._service_account_email)\n\n    @property\n    def requires_scopes(self):\n        \"\"\"Checks if the credentials requires scopes.\n\n        Returns:\n            bool: True if there are no scopes set otherwise False.\n        \"\"\"\n        return True if not self._scopes else False\n\n    @_helpers.copy_docstring(credentials.Scoped)\n    def with_scopes(self, scopes):\n        return Credentials(\n            self._signer,\n            service_account_email=self._service_account_email,\n            scopes=scopes,\n            token_uri=self._token_uri,\n            subject=self._subject,\n            additional_claims=self._additional_claims.copy())\n\n    def with_subject(self, subject):\n        \"\"\"Create a copy of these credentials with the specified subject.\n\n        Args:\n            subject (str): The subject claim.\n\n        Returns:\n            google.auth.service_account.Credentials: A new credentials\n                instance.\n        \"\"\"\n        return Credentials(\n            self._signer,\n            service_account_email=self._service_account_email,\n            scopes=self._scopes,\n            token_uri=self._token_uri,\n            subject=subject,\n            additional_claims=self._additional_claims.copy())\n\n    def _make_authorization_grant_assertion(self):\n        \"\"\"Create the OAuth 2.0 assertion.\n\n        This assertion is used during the OAuth 2.0 grant to acquire an\n        access token.\n\n        Returns:\n            bytes: The authorization grant assertion.\n        \"\"\"\n        now = _helpers.utcnow()\n        lifetime = datetime.timedelta(seconds=_DEFAULT_TOKEN_LIFETIME_SECS)\n        expiry = now + lifetime\n\n        payload = {\n            'iat': _helpers.datetime_to_secs(now),\n            'exp': _helpers.datetime_to_secs(expiry),\n            # The issuer must be the service account email.\n            'iss': self._service_account_email,\n            # The audience must be the auth token endpoint's URI\n            'aud': self._token_uri,\n            'scope': _helpers.scopes_to_string(self._scopes or ())\n        }\n\n        payload.update(self._additional_claims)\n\n        # The subject can be a user email for domain-wide delegation.\n        if self._subject:\n            payload.setdefault('sub', self._subject)\n\n        token = jwt.encode(self._signer, payload)\n\n        return token\n\n    @_helpers.copy_docstring(credentials.Credentials)\n    def refresh(self, request):\n        assertion = self._make_authorization_grant_assertion()\n        access_token, expiry, _ = _client.jwt_grant(\n            request, self._token_uri, assertion)\n        self.token = access_token\n        self.expiry = expiry\n\n    @_helpers.copy_docstring(credentials.Signing)\n    def sign_bytes(self, message):\n        return self._signer.sign(message)\n", "path": "google/oauth2/service_account.py"}]}