Fix github app authentication to work with checks API endpoints (2)

In the last version of this change I forgot a use case when the app is
not installed for a specific project and thus no token can be retrieved.
In this case we must not set the AppInstallationTokenAuth header on the
github session as this will break the fallback to anonymous.
Taking a look on how github3.py handles this use case stated out that
they just don't set any auth header in case the token is missing [1].

Thus, in here we now only set the auth header when we have a token.

This is an improved version of commit
037f2ce537

[1] 96211751ad/src/github3/session.py (L213)

Change-Id: I19557338f847c8af7a8d753b42b497065bc087be
This commit is contained in:
Felix Edel 2020-02-12 08:21:25 +01:00
parent 2106a72691
commit 35595165ff
No known key found for this signature in database
GPG Key ID: E95717A102DD3030
1 changed files with 30 additions and 1 deletions

View File

@ -34,6 +34,7 @@ import jwt
import requests
import github3
import github3.exceptions
from github3.session import AppInstallationTokenAuth
from zuul.connection import BaseConnection
from zuul.lib.gearworker import ZuulGearWorker
@ -1016,7 +1017,35 @@ class GithubConnection(BaseConnection):
# if you're authenticating for a project and you're an integration then
# you need to use the installation specific token.
if project and self.app_id:
github.login(token=self._get_installation_key(project))
# Call get_installation_key to ensure the token gets refresehd in
# case it's expired.
token = self._get_installation_key(project)
# Only set the auth header if we have a token. If not, just don't
# set any auth header so we will be treated as anonymous. That's
# also what the github.login() method would do if the token is not
# set.
if token:
# To set the AppInstallationAuthToken on the github session, we
# also need the expiry date, but in the correct ISO format.
installation_id = self.installation_map.get(project)
_, expiry = self.installation_token_cache.get(installation_id)
format_expiry = datetime.datetime.strftime(
expiry, "%Y-%m-%dT%H:%M:%SZ"
)
# Usually one should use github.login_as_app_installation() to
# authenticate as github app. This method will then request the
# access token for the installation or refresh it if necessary
# and set the correct class on the github.session.auth
# attribute to be identified as github app. As we are already
# managing the installation tokens by ourselves, we just have
# to set the correct TokenAuth class on the github.session.auth
# attribute.
github.session.auth = AppInstallationTokenAuth(
token, format_expiry
)
github._zuul_project = project
github._zuul_user_id = self.installation_map.get(project)