※当サイトの記事には、広告・プロモーションが含まれます。

PythonのライブラリPyGitHubでGitHub AppのInstallation Access Tokenを発行してみる

gigazine.net

イギリスのMRC脳ネットワークダイナミクスユニットとオックスフォード大学による研究で、脳の学習原理が人工知能のものとは根本的に異なってることが示されています。

脳の学習原理は人工知能のものとは根本的に異なっている - GIGAZINE

研究チームは、学習中の脳のニューロンの挙動やシナプス結合の変化を説明する情報処理モデルを調べて分析、シミュレートし、人工のニューラルネットワークとは根本的に異なる原理であることを発見しました。

脳の学習原理は人工知能のものとは根本的に異なっている - GIGAZINE

⇧ 根本的に異なるであろうことは誰もが思っていたでしょうけど、漸く、科学的に検証された感じなんですね。

人間の脳の研究も進むと良いですな。

PyGitHubとは

職場の方に教えていただき、「PyGitHub」というライブラリの存在を知ったので、備忘録として。

公式のドキュメントによりますと、

github.com

PyGitHub is a Python library to access the GitHub REST API. This library enables you to manage GitHub resources such as repositories, user profiles, and organizations in your Python applications.

https://github.com/PyGithub/PyGithub

⇧「GitHub」の「REST API」を「Python」から実行できるようにしているライブラリであると。

「GitHub App」の「Installation Access Token」を取得するには、

pygithub.readthedocs.io

⇧「Installation ID」を取得後、

pygithub.readthedocs.io

⇧ 上記のメソッドを呼ぶことになるんだと思われるのだが、引数の「permissions」の指定が意味不明過ぎるんよね...

ソースコードを確認したところ、

github.com

â– https://github.com/PyGithub/PyGithub/blob/main/github/GithubIntegration.py#L245

############################ Copyrights and license ############################
#                                                                              #
# Copyright 2023 Denis Blanchette <[email protected]>                      #
# Copyright 2023 Enrico Minack <[email protected]>                      #
# Copyright 2023 Hemslo Wang <[email protected]>                           #
# Copyright 2023 Jirka Borovec <[email protected]>        #
# Copyright 2023 Mark Amery <[email protected]>                         #
# Copyright 2023 Trim21 <[email protected]>                                  #
# Copyright 2023 chantra <[email protected]>                    #
# Copyright 2024 Enrico Minack <[email protected]>                      #
# Copyright 2024 Jirka Borovec <[email protected]>        #
# Copyright 2024 Min RK <[email protected]>                                 #
#                                                                              #
# 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 <http://www.gnu.org/licenses/>.             #
#                                                                              #
################################################################################

from __future__ import annotations

import urllib.parse
import warnings
from typing import Any

import deprecated
import urllib3
from urllib3 import Retry

import github
from github import Consts
from github.Auth import AppAuth
from github.GithubApp import GithubApp
from github.GithubException import GithubException
from github.Installation import Installation
from github.InstallationAuthorization import InstallationAuthorization
from github.PaginatedList import PaginatedList
from github.Requester import Requester


class GithubIntegration:
    """
    Main class to obtain tokens for a GitHub integration.
    """

    # keep non-deprecated arguments in-sync with Requester
    # v3: remove integration_id, private_key, jwt_expiry, jwt_issued_at and jwt_algorithm
    # v3: move auth to the front of arguments
    # v3: move * before first argument so all arguments must be named,
    #     allows to reorder / add new arguments / remove deprecated arguments without breaking user code
    #     added here to force named parameters because new parameters have been added
    auth: AppAuth
    base_url: str
    __requester: Requester

    def __init__(
        self,
        integration_id: int | str | None = None,
        private_key: str | None = None,
        base_url: str = Consts.DEFAULT_BASE_URL,
        *,
        timeout: int = Consts.DEFAULT_TIMEOUT,
        user_agent: str = Consts.DEFAULT_USER_AGENT,
        per_page: int = Consts.DEFAULT_PER_PAGE,
        verify: bool | str = True,
        retry: int | Retry | None = None,
        pool_size: int | None = None,
        seconds_between_requests: float | None = Consts.DEFAULT_SECONDS_BETWEEN_REQUESTS,
        seconds_between_writes: float | None = Consts.DEFAULT_SECONDS_BETWEEN_WRITES,
        jwt_expiry: int = Consts.DEFAULT_JWT_EXPIRY,
        jwt_issued_at: int = Consts.DEFAULT_JWT_ISSUED_AT,
        jwt_algorithm: str = Consts.DEFAULT_JWT_ALGORITHM,
        auth: AppAuth | None = None,
        # v3: set lazy = True as the default
        lazy: bool = False,
    ) -> None:
        """
        :param integration_id: int deprecated, use auth=github.Auth.AppAuth(...) instead
        :param private_key: string deprecated, use auth=github.Auth.AppAuth(...) instead
        :param base_url: string
        :param timeout: integer
        :param user_agent: string
        :param per_page: int
        :param verify: boolean or string
        :param retry: int or urllib3.util.retry.Retry object
        :param pool_size: int
        :param seconds_between_requests: float
        :param seconds_between_writes: float
        :param jwt_expiry: int deprecated, use auth=github.Auth.AppAuth(...) instead
        :param jwt_issued_at: int deprecated, use auth=github.Auth.AppAuth(...) instead
        :param jwt_algorithm: string deprecated, use auth=github.Auth.AppAuth(...) instead
        :param auth: authentication method
        :param lazy: completable objects created from this instance are lazy,
                     as well as completable objects created from those, and so on
        """
        if integration_id is not None:
            assert isinstance(integration_id, (int, str)), integration_id
        if private_key is not None:
            assert isinstance(private_key, str), "supplied private key should be a string"
        assert isinstance(base_url, str), base_url
        assert isinstance(timeout, int), timeout
        assert user_agent is None or isinstance(user_agent, str), user_agent
        assert isinstance(per_page, int), per_page
        assert isinstance(verify, (bool, str)), verify
        assert retry is None or isinstance(retry, int) or isinstance(retry, urllib3.util.Retry), retry
        assert pool_size is None or isinstance(pool_size, int), pool_size
        assert seconds_between_requests is None or seconds_between_requests >= 0
        assert seconds_between_writes is None or seconds_between_writes >= 0
        assert isinstance(jwt_expiry, int), jwt_expiry
        assert Consts.MIN_JWT_EXPIRY <= jwt_expiry <= Consts.MAX_JWT_EXPIRY, jwt_expiry
        assert isinstance(jwt_issued_at, int)
        assert isinstance(lazy, bool), lazy

        self.base_url = base_url

        if (
            integration_id is not None
            or private_key is not None
            or jwt_expiry != Consts.DEFAULT_JWT_EXPIRY
            or jwt_issued_at != Consts.DEFAULT_JWT_ISSUED_AT
            or jwt_algorithm != Consts.DEFAULT_JWT_ALGORITHM
        ):
            warnings.warn(
                "Arguments integration_id, private_key, jwt_expiry, jwt_issued_at and jwt_algorithm are deprecated, "
                "please use auth=github.Auth.AppAuth(...) instead",
                category=DeprecationWarning,
            )
            auth = AppAuth(
                integration_id,  # type: ignore
                private_key,  # type: ignore
                jwt_expiry=jwt_expiry,
                jwt_issued_at=jwt_issued_at,
                jwt_algorithm=jwt_algorithm,
            )

        assert isinstance(
            auth, AppAuth
        ), f"GithubIntegration requires github.Auth.AppAuth authentication, not {type(auth)}"

        self.auth = auth

        self.__requester = Requester(
            auth=auth,
            base_url=self.base_url,
            timeout=timeout,
            user_agent=user_agent,
            per_page=per_page,
            verify=verify,
            retry=retry,
            pool_size=pool_size,
            seconds_between_requests=seconds_between_requests,
            seconds_between_writes=seconds_between_writes,
            lazy=lazy,
        )

    def withLazy(self, lazy: bool) -> GithubIntegration:
        """
        Create a GithubIntegration instance with identical configuration but the given lazy setting.

        :param lazy: completable objects created from this instance are lazy, as well as completable objects created
            from those, and so on
        :return: new Github instance

        """
        kwargs = self.__requester.kwargs
        kwargs.update(lazy=lazy)
        return GithubIntegration(**kwargs)

    def close(self) -> None:
        """Close connections to the server. Alternatively, use the
        GithubIntegration object as a context manager:

        .. code-block:: python

          with github.GithubIntegration(...) as gi:
            # do something
        """
        self.__requester.close()

    def __enter__(self) -> GithubIntegration:
        return self

    def __exit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None:
        self.close()

    def get_github_for_installation(
        self, installation_id: int, token_permissions: dict[str, str] | None = None
    ) -> github.Github:
        # The installation has to authenticate as an installation, not an app
        auth = self.auth.get_installation_auth(installation_id, token_permissions, self.__requester)
        return github.Github(**self.__requester.withAuth(auth).kwargs)

    @property
    def requester(self) -> Requester:
        """
        Return my Requester object.

        For example, to make requests to API endpoints not yet supported by PyGitHub.

        """
        return self.__requester

    def _get_headers(self) -> dict[str, str]:
        """
        Get headers for the requests.
        """
        return {
            "Accept": Consts.mediaTypeIntegrationPreview,
        }

    def _get_installed_app(self, url: str) -> Installation:
        """
        Get installation for the given URL.
        """
        headers, response = self.__requester.requestJsonAndCheck("GET", url, headers=self._get_headers())

        return Installation(
            requester=self.__requester,
            headers=headers,
            attributes=response,
        )

    @deprecated.deprecated(
        "Use github.Github(auth=github.Auth.AppAuth), github.Auth.AppAuth.token or github.Auth.AppAuth.create_jwt(expiration) instead"
    )
    def create_jwt(self, expiration: int | None = None) -> str:
        """
        Create a signed JWT
        https://docs.github.com/en/developers/apps/building-github-apps/authenticating-with-github-apps#authenticating-as-a-github-app
        """
        return self.auth.create_jwt(expiration)

    def get_access_token(
        self, installation_id: int, permissions: dict[str, str] | None = None
    ) -> InstallationAuthorization:
        """
        :calls: `POST /app/installations/{installation_id}/access_tokens <https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app>`
        """
        if permissions is None:
            permissions = {}

        if not isinstance(permissions, dict):
            raise GithubException(status=400, data={"message": "Invalid permissions"}, headers=None)

        body = {"permissions": permissions}
        headers, response = self.__requester.requestJsonAndCheck(
            "POST",
            f"/app/installations/{installation_id}/access_tokens",
            headers=self._get_headers(),
            input=body,
        )

        return InstallationAuthorization(
            requester=self.__requester,
            headers=headers,
            attributes=response,
        )

    @deprecated.deprecated("Use get_repo_installation")
    def get_installation(self, owner: str, repo: str) -> Installation:
        """
        Deprecated by get_repo_installation.

        :calls:`GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-
        installation-for-the-authenticated-app>`
        :calls:`GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-
        installation-for-the-authenticated-app>`

        """
        owner = urllib.parse.quote(owner)
        repo = urllib.parse.quote(repo)
        return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation")

    def get_installations(self) -> PaginatedList[Installation]:
        """
        :calls: GET /app/installations <https://docs.github.com/en/rest/reference/apps#list-installations-for-the-authenticated-app>
        """
        return PaginatedList(
            contentClass=Installation,
            requester=self.__requester,
            firstUrl="/app/installations",
            firstParams=None,
            headers=self._get_headers(),
            list_item="installations",
        )

    def get_org_installation(self, org: str) -> Installation:
        """
        :calls: `GET /orgs/{org}/installation <https://docs.github.com/en/rest/apps/apps#get-an-organization-installation-for-the-authenticated-app>`
        """
        org = urllib.parse.quote(org)
        return self._get_installed_app(url=f"/orgs/{org}/installation")

    def get_repo_installation(self, owner: str, repo: str) -> Installation:
        """
        :calls: `GET /repos/{owner}/{repo}/installation <https://docs.github.com/en/rest/reference/apps#get-a-repository-installation-for-the-authenticated-app>`
        """
        owner = urllib.parse.quote(owner)
        repo = urllib.parse.quote(repo)
        return self._get_installed_app(url=f"/repos/{owner}/{repo}/installation")

    def get_user_installation(self, username: str) -> Installation:
        """
        :calls: `GET /users/{username}/installation <https://docs.github.com/en/rest/apps/apps#get-a-user-installation-for-the-authenticated-app>`
        """
        username = urllib.parse.quote(username)
        return self._get_installed_app(url=f"/users/{username}/installation")

    def get_app_installation(self, installation_id: int) -> Installation:
        """
        :calls: `GET /app/installations/{installation_id} <https://docs.github.com/en/rest/apps/apps#get-an-installation-for-the-authenticated-app>`
        """
        return self._get_installed_app(url=f"/app/installations/{installation_id}")

    def get_app(self) -> GithubApp:
        """
        :calls: `GET /app <https://docs.github.com/en/rest/reference/apps#get-the-authenticated-app>`_
        """

        headers, data = self.__requester.requestJsonAndCheck("GET", "/app", headers=self._get_headers())
        return GithubApp(requester=self.__requester, headers=headers, attributes=data, completed=True)    

⇧ とあり、『https://docs.github.com/en/rest/apps/apps#create-an-installation-access-token-for-an-app』を確認すると、

docs.github.com

⇧ なるほど、「GitHub App」の「permission」の設定のことっぽいですな。

docs.github.com

必要に応じて、permissions 本文パラメーターを使って、インストール アクセス トークンに必要なアクセス許可を指定します。 permissions が指定されていない場合、インストール アクセス トークンには、アプリに付与されたすべてのアクセス許可が付与されます。 インストール アクセス トークンに、アプリが付与されていないアクセス許可を付与することはできません。

https://docs.github.com/ja/apps/creating-github-apps/authenticating-with-a-github-app/authenticating-as-a-github-app-installation

⇧ とあるのだけど、具体的な設定できる値について、どこを参照すれば良いのかサッパリ分からない...

PythonのライブラリPyGitHubでGitHub AppのInstallation Access Tokenを発行してみる

とりあえず、例の如く、「WSL 2(Windows Subsystem for Linux 2)」にインストールしている「Rocky Linux 9」の環境で試してみる。

ts0818.hatenablog.com

⇧ 前回の環境にライブラリを追加していくことにします。

事前に、「GitHub App」を作成して「権限」を設定し、「Gitリポジトリ」を「GitHub App」に所属させておく必要はある。

「GitHub App」と「Gitリポジトリ」の関係などは、

ts0818.hatenablog.com

⇧ 上記の記事をご参照ください。

では、「PyGitHub」をインストール。

以下のようなファイルを作成。

ソースコードは以下のような感じ。かなり適当です。

â– /home/ts0818/work/app/python/app/src/main/py/api/service/rest/pygithub/pygithub_service.py

from github import Auth
from github import GithubIntegration
from github import InstallationAuthorization

class PyGitHubService:

    @staticmethod
    def app_auth(app_id:str, private_pem_key_contents: str):
        auth = Auth.AppAuth(app_id, private_pem_key_contents)
        gi = GithubIntegration(auth=auth)
        return gi
    
    @staticmethod
    def get_installation_id(gi:GithubIntegration):
        for installation in gi.get_installations():
            return installation.id
    
    @staticmethod
    def get_installation_access_token(gi:GithubIntegration, installation_id:int):
        result:InstallationAuthorization = gi.get_access_token(installation_id)
        return result.token

pytest用のコード。

â– /home/ts0818/work/app/python/app/src/test/py/api/service/rest/pygithub/test_pygithub_service.py

import pytest
import logging
from github import GithubIntegration
from src.main.py.api.service.rest.pygithub.pygithub_service import PyGitHubService

class TestPyGitHubService:
    logger = logging.getLogger(__name__)

    def test_get_token(self, caplog):
        caplog.set_level(logging.DEBUG)
        TestPyGitHubService.logger.info("[start]test_get_token")
        github_app_id = "GitHub AppのApp IDの値"
        github_app_private_pem_file_path = "/home/ts0818/work/app/python/app/test-github-app.pem"

        with open(github_app_private_pem_file_path) as pem_file:
            private_key_contents = pem_file.read()

        gi:GithubIntegration = PyGitHubService.app_auth(github_app_id, private_key_contents)

        installation_id:int = PyGitHubService.get_installation_id(gi)

        token:str = PyGitHubService.get_installation_access_token(gi, installation_id)
        TestPyGitHubService.logger.info(f"\nâ– â– â–  token â– â– â– \n {token}")

        assert token != None

        log = caplog.text
        TestPyGitHubService.logger.info("log: {log}")
        TestPyGitHubService.logger.info("[finish]test_get_token")

で、実行。

とりあえず、公式のドキュメントが分かり辛い...

ネットの情報を漁っていたところ、

qiita.com

⇧ ボヤいている方がおられたので、一般的に分かり辛いと感じるのが自然のようだ。

所感としては、メソッドの引数、戻り値から抽出する部分とかの説明が欲しい気がする...

Pythonに詳しい人ならソースコードから読解する感じになるんだろうけど、Python素人の我輩にはソースコードを読み解けってのは辛いのよね...

手軽に使えなかったら、ライブラリの意味が無い気もしますしな...

毎度モヤモヤ感が半端ない…

今回はこのへんで。

 

Â