From 61808da15e8e3bcb660acd0e7947326a4a6c0c7a Mon Sep 17 00:00:00 2001 From: Rigas Papathanasopoulos Date: Fri, 20 Dec 2019 01:21:01 +0200 Subject: [PATCH 1/3] Extend installation attributes --- github/AuthenticatedUser.py | 15 ++++++++ github/Installation.py | 36 ++++++++++++++++++- tests/AuthenticatedUser.py | 8 +++++ tests/GithubIntegration.py | 4 +-- .../AuthenticatedUser.testInstallations.txt | 11 ++++++ 5 files changed, 71 insertions(+), 3 deletions(-) create mode 100644 tests/ReplayData/AuthenticatedUser.testInstallations.txt diff --git a/github/AuthenticatedUser.py b/github/AuthenticatedUser.py index dacbd664..35cbb22b 100644 --- a/github/AuthenticatedUser.py +++ b/github/AuthenticatedUser.py @@ -21,6 +21,7 @@ # Copyright 2018 bryanhuntesl <31992054+bryanhuntesl@users.noreply.github.com> # # Copyright 2018 sfdye # # Copyright 2018 itsbruce # +# Copyright 2019 Rigas Papathanasopoulos # # # # This file is part of PyGithub. # # http://pygithub.readthedocs.io/ # @@ -1108,6 +1109,20 @@ class AuthenticatedUser(github.GithubObject.CompletableGithubObject): github.Repository.Repository, self._requester, "/user/subscriptions", None ) + def get_installations(self): + """ + :calls: `GET /user/installations `_ + :rtype: :class:`github.PaginatedList.PaginatedList` of :class:`github.Installation.Installation` + """ + return github.PaginatedList.PaginatedList( + github.Installation.Installation, + self._requester, + "/user/installations", + None, + headers={"Accept": Consts.mediaTypeIntegrationPreview}, + list_item="installations", + ) + def has_in_following(self, following): """ :calls: `GET /user/following/:user `_ diff --git a/github/Installation.py b/github/Installation.py index b83049b9..785d9394 100644 --- a/github/Installation.py +++ b/github/Installation.py @@ -6,6 +6,7 @@ # Copyright 2017 Simon # # Copyright 2018 Wan Liuyang # # Copyright 2018 sfdye # +# Copyright 2019 Rigas Papathanasopoulos # # # # This file is part of PyGithub. # # http://pygithub.readthedocs.io/ # @@ -52,7 +53,31 @@ class Installation(github.GithubObject.NonCompletableGithubObject): @property def id(self): - return self._id + """ + :type: integer + """ + return self._id.value + + @property + def app_id(self): + """ + :type: integer + """ + return self._app_id.value + + @property + def target_id(self): + """ + :type: integer + """ + return self._target_id.value + + @property + def target_type(self): + """ + :type: string + """ + return self._target_type.value def get_repos(self): """ @@ -72,7 +97,16 @@ class Installation(github.GithubObject.NonCompletableGithubObject): def _initAttributes(self): self._id = github.GithubObject.NotSet + self._app_id = github.GithubObject.NotSet + self._target_id = github.GithubObject.NotSet + self._target_type = github.GithubObject.NotSet def _useAttributes(self, attributes): if "id" in attributes: # pragma no branch self._id = self._makeIntAttribute(attributes["id"]) + if "app_id" in attributes: # pragma no branch + self._app_id = self._makeIntAttribute(attributes["app_id"]) + if "target_id" in attributes: # pragma no branch + self._target_id = self._makeIntAttribute(attributes["target_id"]) + if "target_type" in attributes: # pragma no branch + self._target_type = self._makeStringAttribute(attributes["target_type"]) diff --git a/tests/AuthenticatedUser.py b/tests/AuthenticatedUser.py index 2ec2de2b..9fb4e2ae 100644 --- a/tests/AuthenticatedUser.py +++ b/tests/AuthenticatedUser.py @@ -741,3 +741,11 @@ class AuthenticatedUser(Framework.TestCase): def testGetMigrations(self): self.assertEqual(self.user.get_migrations().totalCount, 46) + + def testInstallations(self): + installations = self.user.get_installations() + self.assertEqual(installations[0].id, 123456) + self.assertEqual(installations[0].app_id, 10101) + self.assertEqual(installations[0].target_id, 3344556) + self.assertEqual(installations[0].target_type, "User") + self.assertEqual(installations.totalCount, 1) diff --git a/tests/GithubIntegration.py b/tests/GithubIntegration.py index dff05cc5..e5f22a22 100644 --- a/tests/GithubIntegration.py +++ b/tests/GithubIntegration.py @@ -164,7 +164,7 @@ class GithubIntegration(unittest.TestCase): self.get_mock.calls[0][0], ("https://api.github.com/repos/foo/bar/installation",), ) - self.assertEqual(inst.id.value, 111111) + self.assertEqual(inst.id, 111111) def test_get_installation_custom_base_url(self): from github import GithubIntegration @@ -175,7 +175,7 @@ class GithubIntegration(unittest.TestCase): self.get_mock.calls[0][0], ("https://corp.com/v3/repos/foo/bar/installation",), ) - self.assertEqual(inst.id.value, 111111) + self.assertEqual(inst.id, 111111) def tearDown(self): GithubObject.setCheckAfterInitFlag(self.origin_check_after_init_flag) diff --git a/tests/ReplayData/AuthenticatedUser.testInstallations.txt b/tests/ReplayData/AuthenticatedUser.testInstallations.txt new file mode 100644 index 00000000..365b5050 --- /dev/null +++ b/tests/ReplayData/AuthenticatedUser.testInstallations.txt @@ -0,0 +1,11 @@ +https +GET +api.github.com +None +/user/installations +{'Accept': 'application/vnd.github.machine-man-preview+json', 'Authorization': 'Basic login_and_password_removed', 'User-Agent': 'PyGithub/Python'} +None +200 +[('Server', 'GitHub.com'), ('Date', 'Wed, 23 Jan 2019 22:55:08 GMT'), ('Content-Type', 'application/json; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Status', '200 OK'), ('X-RateLimit-Limit', '5000'), ('X-RateLimit-Remaining', '4999'), ('X-RateLimit-Reset', '1548287423'), ('Cache-Control', 'private, max-age=60, s-maxage=60'), ('Vary', 'Accept, Authorization, Cookie, X-GitHub-OTP'), ('ETag', 'W/"a5a8c1fcbecacfdb17b4b714f28556ba"'), ('X-OAuth-Scopes', ''), ('X-Accepted-OAuth-Scopes', ''), ('X-OAuth-Client-Id', 'Iv1.11b0acc03bd76665'), ('X-GitHub-Media-Type', 'github.machine-man-preview; format=json'), ('Access-Control-Expose-Headers', 'ETag, Link, Location, Retry-After, X-GitHub-OTP, X-RateLimit-Limit, X-RateLimit-Remaining, X-RateLimit-Reset, X-OAuth-Scopes, X-Accepted-OAuth-Scopes, X-Poll-Interval, X-GitHub-Media-Type'), ('Access-Control-Allow-Origin', '*'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '1; mode=block'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Content-Security-Policy', "default-src 'none'"), ('Content-Encoding', 'gzip')] +{"total_count":1,"installations":[{"id":123456,"account":{"login":"rigaspapas","id":12345,"node_id":"MDQ6VXNlcjE3NzM2NTI=","avatar_url":"https://avatars1.githubusercontent.com/u/12345?v=4","gravatar_id":"","url":"https://api.github.com/users/rigaspapas","html_url":"https://github.com/rigaspapas","followers_url":"https://api.github.com/users/rigaspapas/followers","following_url":"https://api.github.com/users/rigaspapas/following{/other_user}","gists_url":"https://api.github.com/users/rigaspapas/gists{/gist_id}","starred_url":"https://api.github.com/users/rigaspapas/starred{/owner}{/repo}","subscriptions_url":"https://api.github.com/users/rigaspapas/subscriptions","organizations_url":"https://api.github.com/users/rigaspapas/orgs","repos_url":"https://api.github.com/users/rigaspapas/repos","events_url":"https://api.github.com/users/rigaspapas/events{/privacy}","received_events_url":"https://api.github.com/users/rigaspapas/received_events","type":"User","site_admin":false},"repository_selection":"selected","access_tokens_url":"https://api.github.com/installations/242638/access_tokens","repositories_url":"https://api.github.com/installation/repositories","html_url":"https://github.com/settings/installations/123456","app_id":10101,"target_id":3344556,"target_type":"User","permissions":{"contents":"write","pull_requests":"write","administration":"read","metadata":"read","statuses":"read"},"events":["push"],"created_at":"2018-07-13T17:59:47.000+03:00","updated_at":"2018-07-13T17:59:47.000+03:00","single_file_name":null}]} + From 4a6468aa4a471a4fe8ba02164a4188a6a8d216fd Mon Sep 17 00:00:00 2001 From: Rigas Papathanasopoulos Date: Fri, 20 Dec 2019 01:21:17 +0200 Subject: [PATCH 2/3] Create AccessToken entity This class is used to represent access tokens created from a successful OAuth authorization process. --- github/AccessToken.py | 74 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 74 insertions(+) create mode 100644 github/AccessToken.py diff --git a/github/AccessToken.py b/github/AccessToken.py new file mode 100644 index 00000000..8ebbe277 --- /dev/null +++ b/github/AccessToken.py @@ -0,0 +1,74 @@ +# -*- coding: utf-8 -*- + +############################ Copyrights and license ############################ +# # +# Copyright 2019 Rigas Papathanasopoulos # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +import github.GithubObject + + +class AccessToken(github.GithubObject.NonCompletableGithubObject): + """ + This class represents access tokens. + """ + + def __repr__(self): + return self.get__repr__( + { + "token": "{}...".format(self.token[:5]), + "scope": self.scope, + "type": self.type, + } + ) + + @property + def token(self): + """ + :type: string + """ + return self._token.value + + @property + def type(self): + """ + :type: string + """ + return self._type.value + + @property + def scope(self): + """ + :type: string + """ + return self._scope.value + + def _initAttributes(self): + self._token = github.GithubObject.NotSet + self._type = github.GithubObject.NotSet + self._scope = github.GithubObject.NotSet + + def _useAttributes(self, attributes): + if "access_token" in attributes: # pragma no branch + self._token = self._makeStringAttribute(attributes["access_token"]) + if "token_type" in attributes: # pragma no branch + self._type = self._makeStringAttribute(attributes["token_type"]) + if "scope" in attributes: # pragma no branch + self._scope = self._makeStringAttribute(attributes["scope"]) From 4b4371101748f7d7f41c313d1b187bb9aa828b52 Mon Sep 17 00:00:00 2001 From: Rigas Papathanasopoulos Date: Fri, 20 Dec 2019 01:21:23 +0200 Subject: [PATCH 3/3] Add OAuth support for GitHub applications Create the ApplicationOAuth class which is responsible for handling a GitHub application's OAuth authorization process. --- github/ApplicationOAuth.py | 114 ++++++++++++++++++ github/MainClass.py | 10 ++ github/Requester.py | 1 + tests/ApplicationOAuth.py | 71 +++++++++++ .../ApplicationOAuth.testGetAccessToken.txt | 11 ++ 5 files changed, 207 insertions(+) create mode 100644 github/ApplicationOAuth.py create mode 100644 tests/ApplicationOAuth.py create mode 100644 tests/ReplayData/ApplicationOAuth.testGetAccessToken.txt diff --git a/github/ApplicationOAuth.py b/github/ApplicationOAuth.py new file mode 100644 index 00000000..0afe771a --- /dev/null +++ b/github/ApplicationOAuth.py @@ -0,0 +1,114 @@ +# -*- coding: utf-8 -*- + +############################ Copyrights and license ########################### +# # +# Copyright 2019 Rigas Papathanasopoulos # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more# +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +############################################################################### + +import urllib + +import github.GithubObject +from github.AccessToken import AccessToken + + +class ApplicationOAuth(github.GithubObject.NonCompletableGithubObject): + """ + This class is used for identifying and authorizing users for Github Apps. + https://developer.github.com/apps/building-github-apps/identifying-and-authorizing-users-for-github-apps/#1-users-are-redirected-to-request-their-github-identity + """ + + def __repr__(self): + return self.get__repr__({"client_id": self._client_id.value}) + + @property + def client_id(self): + return self._client_id.value + + @property + def client_secret(self): + return self._client_secret.value + + def _initAttributes(self): + self._client_id = github.GithubObject.NotSet + self._client_secret = github.GithubObject.NotSet + + def _useAttributes(self, attributes): + if "client_id" in attributes: # pragma no branch + self._client_id = self._makeStringAttribute(attributes["client_id"]) + if "client_secret" in attributes: # pragma no branch + self._client_secret = self._makeStringAttribute(attributes["client_secret"]) + + def get_login_url(self, redirect_uri=None, state=None, login=None): + """ + Return the URL you need to redirect a user to in order to authorize + your App. + :type: string + """ + parameters = {"client_id": self.client_id} + if redirect_uri is not None: + assert isinstance(redirect_uri, str), redirect_uri + parameters["redirect_uri"] = redirect_uri + if state is not None: + assert isinstance(state, str), state + parameters["state"] = state + if login is not None: + assert isinstance(login, str), login + parameters["login"] = login + + parameters = urllib.parse.urlencode(parameters) + + base_url = "https://github.com/login/oauth/authorize" + return u"{}?{}".format(base_url, parameters) + + def get_access_token(self, code, state=None): + """ + :calls: `POST /login/oauth/access_token `_ + :param code: string + :param state: string + """ + assert isinstance(code, str), code + post_parameters = { + "code": code, + "client_id": self.client_id, + "client_secret": self.client_secret, + } + + if state is not None: + post_parameters["state"] = state + + self._requester._Requester__authorizationHeader = None + headers, data = self._requester.requestJsonAndCheck( + "POST", + "https://github.com/login/oauth/access_token", + headers={ + "Accept": "application/json", + "Content-Type": "application/json", + "User-Agent": "PyGithub/Python", + }, + input=post_parameters, + ) + + return AccessToken( + requester=self._requester, + # not required, this is a NonCompletableGithubObject + headers={}, + attributes=data, + completed=False, + ) diff --git a/github/MainClass.py b/github/MainClass.py index 3c643958..f3744435 100644 --- a/github/MainClass.py +++ b/github/MainClass.py @@ -29,6 +29,7 @@ # Copyright 2018 sfdye # # Copyright 2018 itsbruce # # Copyright 2019 Tomas Tomecek # +# Copyright 2019 Rigas Papathanasopoulos # # # # This file is part of PyGithub. # # http://pygithub.readthedocs.io/ # @@ -56,6 +57,7 @@ import jwt import requests import urllib3 +import github.ApplicationOAuth import github.Event import github.Gist import github.GithubObject @@ -757,6 +759,14 @@ class Github(object): self.__requester, headers={}, attributes={"id": id}, completed=True ) + def get_oauth_application(self, client_id, client_secret): + return github.ApplicationOAuth.ApplicationOAuth( + self.__requester, + headers={}, + attributes={"client_id": client_id, "client_secret": client_secret}, + completed=False, + ) + class GithubIntegration(object): """ diff --git a/github/Requester.py b/github/Requester.py index 71a7d192..9f75d22a 100644 --- a/github/Requester.py +++ b/github/Requester.py @@ -538,6 +538,7 @@ class Requester: self.__hostname, "uploads.github.com", "status.github.com", + "github.com", ], o.hostname assert o.path.startswith((self.__prefix, "/api/")) assert o.port == self.__port diff --git a/tests/ApplicationOAuth.py b/tests/ApplicationOAuth.py new file mode 100644 index 00000000..408fd5ab --- /dev/null +++ b/tests/ApplicationOAuth.py @@ -0,0 +1,71 @@ +# -*- coding: utf-8 -*- + +############################ Copyrights and license ############################ +# # +# Copyright 2019 Rigas Papathanasopoulos # +# # +# This file is part of PyGithub. # +# http://pygithub.readthedocs.io/ # +# # +# PyGithub is free software: you can redistribute it and/or modify it under # +# the terms of the GNU Lesser General Public License as published by the Free # +# Software Foundation, either version 3 of the License, or (at your option) # +# any later version. # +# # +# PyGithub is distributed in the hope that it will be useful, but WITHOUT ANY # +# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS # +# FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more # +# details. # +# # +# You should have received a copy of the GNU Lesser General Public License # +# along with PyGithub. If not, see . # +# # +################################################################################ + +from . import Framework + + +class ApplicationOAuth(Framework.TestCase): + def setUp(self): + super().setUp() + self.CLIENT_ID = "client_id_removed" + self.CLIENT_SECRET = "client_secret_removed" + self.app = self.g.get_oauth_application(self.CLIENT_ID, self.CLIENT_SECRET) + + def testLoginURL(self): + BASE_URL = "https://github.com/login/oauth/authorize" + sample_uri = "https://myapp.com/some/path" + sample_uri_encoded = "https%3A%2F%2Fmyapp.com%2Fsome%2Fpath" + self.assertEqual( + self.app.get_login_url(), "{}?client_id={}".format(BASE_URL, self.CLIENT_ID) + ) + self.assertTrue( + "redirect_uri={}".format(sample_uri_encoded) + in self.app.get_login_url(redirect_uri=sample_uri) + ) + self.assertTrue( + "client_id={}".format(self.CLIENT_ID) + in self.app.get_login_url(redirect_uri=sample_uri) + ) + self.assertTrue( + "state=123abc" in self.app.get_login_url(state="123abc", login="user") + ) + self.assertTrue( + "login=user" in self.app.get_login_url(state="123abc", login="user") + ) + self.assertTrue( + "client_id={}".format(self.CLIENT_ID) + in self.app.get_login_url(state="123abc", login="user") + ) + + def testGetAccessToken(self): + access_token = self.app.get_access_token( + "oauth_code_removed", state="state_removed" + ) + # Test string representation + self.assertEqual( + str(access_token), 'AccessToken(type="bearer", token="acces...", scope="")' + ) + self.assertEqual(access_token.token, "access_token_removed") + self.assertEqual(access_token.scope, "") + self.assertEqual(access_token.type, "bearer") diff --git a/tests/ReplayData/ApplicationOAuth.testGetAccessToken.txt b/tests/ReplayData/ApplicationOAuth.testGetAccessToken.txt new file mode 100644 index 00000000..889d4263 --- /dev/null +++ b/tests/ReplayData/ApplicationOAuth.testGetAccessToken.txt @@ -0,0 +1,11 @@ +https +POST +github.com +None +/login/oauth/access_token +{'Content-Type': 'application/json', 'Accept': 'application/json', 'User-Agent': 'PyGithub/Python'} +{"client_secret": "client_secret_removed", "code": "oauth_code_removed", "client_id": "client_id_removed", "state": "state_removed"} +200 +[('Date', 'Fri, 25 Jan 2019 11:06:39 GMT'), ('Content-Type', 'application/json; charset=utf-8'), ('Transfer-Encoding', 'chunked'), ('Server', 'GitHub.com'), ('Status', '200 OK'), ('Vary', 'X-PJAX, Accept-Encoding'), ('ETag', 'W/"deebfe47f0039427b39ec010749014f6"'), ('Cache-Control', 'max-age=0, private, must-revalidate'), ('Set-Cookie', 'has_recent_activity=1; path=/; expires=Fri, 25 Jan 2019 12:06:38 -0000, ignored_unsupported_browser_notice=false; path=/'), ('X-Request-Id', 'ed8794eb-dc95-481f-8e52-2cd5db0494a0'), ('Strict-Transport-Security', 'max-age=31536000; includeSubdomains; preload'), ('X-Frame-Options', 'deny'), ('X-Content-Type-Options', 'nosniff'), ('X-XSS-Protection', '1; mode=block'), ('Referrer-Policy', 'origin-when-cross-origin, strict-origin-when-cross-origin'), ('Expect-CT', 'max-age=2592000, report-uri="https://api.github.com/_private/browser/errors"'), ('Content-Security-Policy', "default-src 'none'; base-uri 'self'; block-all-mixed-content; connect-src 'self' uploads.github.com www.githubstatus.com collector.githubapp.com api.github.com www.google-analytics.com github-cloud.s3.amazonaws.com github-production-repository-file-5c1aeb.s3.amazonaws.com github-production-upload-manifest-file-7fdce7.s3.amazonaws.com github-production-user-asset-6210df.s3.amazonaws.com wss://live.github.com; font-src github.githubassets.com; form-action 'self' github.com gist.github.com; frame-ancestors 'none'; frame-src render.githubusercontent.com; img-src 'self' data: github.githubassets.com assets-cdn.github.com identicons.github.com collector.githubapp.com github-cloud.s3.amazonaws.com *.githubusercontent.com; manifest-src 'self'; media-src 'none'; script-src github.githubassets.com; style-src 'unsafe-inline' github.githubassets.com"), ('Content-Encoding', 'gzip'), ('X-GitHub-Request-Id', 'C8AC:1D8B2:126D746:1BF8DE4:5C4AEDBE')] +{"access_token":"access_token_removed","token_type":"bearer","scope":""} +