############################ Copyrights and license ############################
# #
# Copyright 2012 Andrew Bettison #
# Copyright 2012 Dima Kukushkin #
# Copyright 2012 Michael Woodworth #
# Copyright 2012 Petteri Muilu #
# Copyright 2012 Steve English #
# Copyright 2012 Vincent Jacques #
# Copyright 2012 Zearin #
# Copyright 2013 AKFish #
# Copyright 2013 Cameron White #
# Copyright 2013 Ed Jackson #
# Copyright 2013 Jonathan J Hunt #
# Copyright 2013 Mark Roddy #
# Copyright 2013 Vincent Jacques #
# Copyright 2014 Jimmy Zelinskie #
# Copyright 2014 Vincent Jacques #
# Copyright 2015 Brian Eugley #
# Copyright 2015 Daniel Pocock #
# Copyright 2016 Denis K #
# Copyright 2016 Jared K. Smith #
# Copyright 2016 Mathieu Mitchell #
# Copyright 2016 Peter Buckley #
# Copyright 2017 Chris McBride #
# Copyright 2017 Hugo #
# Copyright 2017 Simon #
# Copyright 2018 Arda Kuyumcu #
# Copyright 2018 Dylan #
# Copyright 2018 Maarten Fonville #
# Copyright 2018 Mike Miller #
# Copyright 2018 R1kk3r #
# Copyright 2018 Shubham Singh <41840111+singh811@users.noreply.github.com> #
# Copyright 2018 Steve Kowalik #
# Copyright 2018 Tuuu Nya #
# Copyright 2018 Wan Liuyang #
# Copyright 2018 sfdye #
# Copyright 2019 Isac Souza #
# Copyright 2019 Rigas Papathanasopoulos #
# Copyright 2019 Steve Kowalik #
# Copyright 2019 Wan Liuyang #
# Copyright 2020 Jesse Li #
# Copyright 2020 Steve Kowalik #
# Copyright 2021 Amador Pahim #
# Copyright 2021 Mark Walker #
# Copyright 2021 Steve Kowalik #
# Copyright 2022 Liuyang Wan #
# Copyright 2023 Denis Blanchette #
# Copyright 2023 Enrico Minack #
# Copyright 2023 Heitor Polidoro #
# Copyright 2023 Hemslo Wang #
# Copyright 2023 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# Copyright 2023 Phillip Tran #
# Copyright 2023 Trim21 #
# Copyright 2023 adosibalo <94008816+adosibalo@users.noreply.github.com> #
# Copyright 2024 Enrico Minack #
# Copyright 2024 Jirka Borovec <6035284+Borda@users.noreply.github.com> #
# #
# 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 io
import json
import logging
import mimetypes
import os
import re
import threading
import time
import urllib
import urllib.parse
from collections import deque
from datetime import datetime, timezone
from io import IOBase
from typing import (
TYPE_CHECKING,
Any,
BinaryIO,
Callable,
Deque,
Dict,
Generic,
ItemsView,
List,
Optional,
Tuple,
Type,
TypeVar,
Union,
)
import requests
import requests.adapters
from urllib3 import Retry
import github.Consts as Consts
import github.GithubException as GithubException
if TYPE_CHECKING:
from .AppAuthentication import AppAuthentication
from .Auth import Auth
from .GithubObject import GithubObject
from .InstallationAuthorization import InstallationAuthorization
T = TypeVar("T")
# For App authentication, time remaining before token expiration to request a new one
ACCESS_TOKEN_REFRESH_THRESHOLD_SECONDS = 20
class RequestsResponse:
# mimic the httplib response object
def __init__(self, r: requests.Response):
self.status = r.status_code
self.headers = r.headers
self.text = r.text
def getheaders(self) -> ItemsView[str, str]:
return self.headers.items()
def read(self) -> str:
return self.text
class HTTPSRequestsConnectionClass:
retry: Union[int, Retry]
# mimic the httplib connection object
def __init__(
self,
host: str,
port: Optional[int] = None,
strict: bool = False,
timeout: Optional[int] = None,
retry: Optional[Union[int, Retry]] = None,
pool_size: Optional[int] = None,
**kwargs: Any,
) -> None:
self.port = port if port else 443
self.host = host
self.protocol = "https"
self.timeout = timeout
self.verify = kwargs.get("verify", True)
self.session = requests.Session()
# having Session.auth set something other than None disables falling back to .netrc file
# https://github.com/psf/requests/blob/d63e94f552ebf77ccf45d97e5863ac46500fa2c7/src/requests/sessions.py#L480-L481
# see https://github.com/PyGithub/PyGithub/pull/2703
self.session.auth = Requester.noopAuth
if retry is None:
self.retry = requests.adapters.DEFAULT_RETRIES
else:
self.retry = retry
if pool_size is None:
self.pool_size = requests.adapters.DEFAULT_POOLSIZE
else:
self.pool_size = pool_size
self.adapter = requests.adapters.HTTPAdapter(
max_retries=self.retry,
pool_connections=self.pool_size,
pool_maxsize=self.pool_size,
)
self.session.mount("https://", self.adapter)
def request(
self,
verb: str,
url: str,
input: Optional[Union[str, io.BufferedReader]],
headers: Dict[str, str],
) -> None:
self.verb = verb
self.url = url
self.input = input
self.headers = headers
def getresponse(self) -> RequestsResponse:
verb = getattr(self.session, self.verb.lower())
url = f"{self.protocol}://{self.host}:{self.port}{self.url}"
r = verb(
url,
headers=self.headers,
data=self.input,
timeout=self.timeout,
verify=self.verify,
allow_redirects=False,
)
return RequestsResponse(r)
def close(self) -> None:
self.session.close()
class HTTPRequestsConnectionClass:
# mimic the httplib connection object
def __init__(
self,
host: str,
port: Optional[int] = None,
strict: bool = False,
timeout: Optional[int] = None,
retry: Optional[Union[int, Retry]] = None,
pool_size: Optional[int] = None,
**kwargs: Any,
):
self.port = port if port else 80
self.host = host
self.protocol = "http"
self.timeout = timeout
self.verify = kwargs.get("verify", True)
self.session = requests.Session()
# having Session.auth set something other than None disables falling back to .netrc file
# https://github.com/psf/requests/blob/d63e94f552ebf77ccf45d97e5863ac46500fa2c7/src/requests/sessions.py#L480-L481
# see https://github.com/PyGithub/PyGithub/pull/2703
self.session.auth = Requester.noopAuth
if retry is None:
self.retry = requests.adapters.DEFAULT_RETRIES
else:
self.retry = retry # type: ignore
if pool_size is None:
self.pool_size = requests.adapters.DEFAULT_POOLSIZE
else:
self.pool_size = pool_size
self.adapter = requests.adapters.HTTPAdapter(
max_retries=self.retry,
pool_connections=self.pool_size,
pool_maxsize=self.pool_size,
)
self.session.mount("http://", self.adapter)
def request(self, verb: str, url: str, input: None, headers: Dict[str, str]) -> None:
self.verb = verb
self.url = url
self.input = input
self.headers = headers
def getresponse(self) -> RequestsResponse:
verb = getattr(self.session, self.verb.lower())
url = f"{self.protocol}://{self.host}:{self.port}{self.url}"
r = verb(
url,
headers=self.headers,
data=self.input,
timeout=self.timeout,
verify=self.verify,
allow_redirects=False,
)
return RequestsResponse(r)
def close(self) -> None:
self.session.close()
class Requester:
__installation_authorization: Optional["InstallationAuthorization"]
__app_auth: Optional["AppAuthentication"]
__httpConnectionClass = HTTPRequestsConnectionClass
__httpsConnectionClass = HTTPSRequestsConnectionClass
__persist = True
__logger: Optional[logging.Logger] = None
_frameBuffer: List[Any]
@staticmethod
def noopAuth(request: requests.models.PreparedRequest) -> requests.models.PreparedRequest:
return request
@classmethod
def injectConnectionClasses(
cls,
httpConnectionClass: Type[HTTPRequestsConnectionClass],
httpsConnectionClass: Type[HTTPSRequestsConnectionClass],
) -> None:
cls.__persist = False
cls.__httpConnectionClass = httpConnectionClass
cls.__httpsConnectionClass = httpsConnectionClass
@classmethod
def resetConnectionClasses(cls) -> None:
cls.__persist = True
cls.__httpConnectionClass = HTTPRequestsConnectionClass
cls.__httpsConnectionClass = HTTPSRequestsConnectionClass
@classmethod
def injectLogger(cls, logger: logging.Logger) -> None:
cls.__logger = logger
@classmethod
def resetLogger(cls) -> None:
cls.__logger = None
#############################################################
# For Debug
@classmethod
def setDebugFlag(cls, flag: bool) -> None:
cls.DEBUG_FLAG = flag
@classmethod
def setOnCheckMe(cls, onCheckMe: Callable) -> None:
cls.ON_CHECK_ME = onCheckMe
DEBUG_FLAG = False
DEBUG_FRAME_BUFFER_SIZE = 1024
DEBUG_HEADER_KEY = "DEBUG_FRAME"
ON_CHECK_ME: Optional[Callable] = None
def NEW_DEBUG_FRAME(self, requestHeader: Dict[str, str]) -> None:
"""
Initialize a debug frame with requestHeader
Frame count is updated and will be attached to respond header
The structure of a frame: [requestHeader, statusCode, responseHeader, raw_data]
Some of them may be None
"""
if self.DEBUG_FLAG: # pragma no branch (Flag always set in tests)
new_frame = [requestHeader, None, None, None]
if self._frameCount < self.DEBUG_FRAME_BUFFER_SIZE - 1: # pragma no branch (Should be covered)
self._frameBuffer.append(new_frame)
else:
self._frameBuffer[0] = new_frame # pragma no cover (Should be covered)
self._frameCount = len(self._frameBuffer) - 1
def DEBUG_ON_RESPONSE(self, statusCode: int, responseHeader: Dict[str, Union[str, int]], data: str) -> None:
"""
Update current frame with response Current frame index will be attached to responseHeader.
"""
if self.DEBUG_FLAG: # pragma no branch (Flag always set in tests)
self._frameBuffer[self._frameCount][1:4] = [
statusCode,
responseHeader,
data,
]
responseHeader[self.DEBUG_HEADER_KEY] = self._frameCount
def check_me(self, obj: "GithubObject") -> None:
if self.DEBUG_FLAG and self.ON_CHECK_ME is not None: # pragma no branch (Flag always set in tests)
frame = None
if self.DEBUG_HEADER_KEY in obj._headers:
frame_index = obj._headers[self.DEBUG_HEADER_KEY]
frame = self._frameBuffer[frame_index] # type: ignore
self.ON_CHECK_ME(obj, frame)
def _initializeDebugFeature(self) -> None:
self._frameCount = 0
self._frameBuffer = []
#############################################################
_frameCount: int
__connectionClass: Union[Type[HTTPRequestsConnectionClass], Type[HTTPSRequestsConnectionClass]]
__hostname: str
__authorizationHeader: Optional[str]
__seconds_between_requests: Optional[float]
__seconds_between_writes: Optional[float]
# keep arguments in-sync with github.MainClass and GithubIntegration
def __init__(
self,
auth: Optional["Auth"],
base_url: str,
timeout: int,
user_agent: str,
per_page: int,
verify: Union[bool, str],
retry: Optional[Union[int, Retry]],
pool_size: Optional[int],
seconds_between_requests: Optional[float] = None,
seconds_between_writes: Optional[float] = None,
):
self._initializeDebugFeature()
self.__auth = auth
self.__base_url = base_url
o = urllib.parse.urlparse(base_url)
self.__graphql_prefix = self.get_graphql_prefix(o.path)
self.__graphql_url = urllib.parse.urlunparse(o._replace(path=self.__graphql_prefix))
self.__hostname = o.hostname # type: ignore
self.__port = o.port
self.__prefix = o.path
self.__timeout = timeout
self.__retry = retry # NOTE: retry can be either int or an urllib3 Retry object
self.__pool_size = pool_size
self.__seconds_between_requests = seconds_between_requests
self.__seconds_between_writes = seconds_between_writes
self.__last_requests: Dict[str, float] = dict()
self.__scheme = o.scheme
if o.scheme == "https":
self.__connectionClass = self.__httpsConnectionClass
elif o.scheme == "http":
self.__connectionClass = self.__httpConnectionClass
else:
assert False, "Unknown URL scheme"
self.__connection: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None
self.__connection_lock = threading.Lock()
self.__custom_connections: Deque[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = deque()
self.rate_limiting = (-1, -1)
self.rate_limiting_resettime = 0
self.FIX_REPO_GET_GIT_REF = True
self.per_page = per_page
self.oauth_scopes = None
assert user_agent is not None, (
"github now requires a user-agent. "
"See https://docs.github.com/en/rest/overview/resources-in-the-rest-api#user-agent-required"
)
self.__userAgent = user_agent
self.__verify = verify
self.__installation_authorization = None
# provide auth implementations that require a requester with this requester
if isinstance(self.__auth, WithRequester):
self.__auth.withRequester(self)
def __getstate__(self) -> Dict[str, Any]:
state = self.__dict__.copy()
# __connection_lock is not picklable
del state["_Requester__connection_lock"]
# __connection is not usable on remote, so ignore it
del state["_Requester__connection"]
# __custom_connections is not usable on remote, so ignore it
del state["_Requester__custom_connections"]
return state
def __setstate__(self, state: Dict[str, Any]) -> None:
self.__dict__.update(state)
self.__connection_lock = threading.Lock()
self.__connection = None
self.__custom_connections = deque()
@staticmethod
# replace with str.removesuffix once support for Python 3.7 is dropped
def remove_suffix(string: str, suffix: str) -> str:
if string.endswith(suffix):
return string[: -len(suffix)]
return string
@staticmethod
def get_graphql_prefix(path: Optional[str]) -> str:
if path is None or path in ["", "/"]:
path = ""
if path.endswith(("/v3", "/v3/")):
path = Requester.remove_suffix(path, "/")
path = Requester.remove_suffix(path, "/v3")
return path + "/graphql"
def close(self) -> None:
"""
Close the connection to the server.
"""
with self.__connection_lock:
if self.__connection is not None:
self.__connection.close()
self.__connection = None
while self.__custom_connections:
self.__custom_connections.popleft().close()
@property
def kwargs(self) -> Dict[str, Any]:
"""
Returns arguments required to recreate this Requester with Requester.__init__, as well as with
MainClass.__init__ and GithubIntegration.__init__.
"""
return dict(
auth=self.__auth,
base_url=self.__base_url,
timeout=self.__timeout,
user_agent=self.__userAgent,
per_page=self.per_page,
verify=self.__verify,
retry=self.__retry,
pool_size=self.__pool_size,
seconds_between_requests=self.__seconds_between_requests,
seconds_between_writes=self.__seconds_between_writes,
)
@property
def base_url(self) -> str:
return self.__base_url
@property
def graphql_url(self) -> str:
return self.__graphql_url
@property
def scheme(self) -> str:
return self.__scheme
@property
def hostname(self) -> str:
return self.__hostname
@property
def hostname_and_port(self) -> str:
if self.__port is None:
return self.hostname
return f"{self.hostname}:{self.__port}"
@property
def auth(self) -> Optional["Auth"]:
return self.__auth
def withAuth(self, auth: Optional["Auth"]) -> "Requester":
"""
Create a new requester instance with identical configuration but the given authentication method.
:param auth: authentication method
:return: new Requester implementation
"""
kwargs = self.kwargs
kwargs.update(auth=auth)
return Requester(**kwargs)
def requestJsonAndCheck(
self,
verb: str,
url: str,
parameters: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, str]] = None,
input: Optional[Any] = None,
) -> Tuple[Dict[str, Any], Any]:
return self.__check(*self.requestJson(verb, url, parameters, headers, input, self.__customConnection(url)))
def requestMultipartAndCheck(
self,
verb: str,
url: str,
parameters: Optional[Dict[str, Any]] = None,
headers: Optional[Dict[str, Any]] = None,
input: Optional[Dict[str, str]] = None,
) -> Tuple[Dict[str, Any], Optional[Dict[str, Any]]]:
return self.__check(*self.requestMultipart(verb, url, parameters, headers, input, self.__customConnection(url)))
def requestBlobAndCheck(
self,
verb: str,
url: str,
parameters: Optional[Dict[str, str]] = None,
headers: Optional[Dict[str, str]] = None,
input: Optional[str] = None,
cnx: Optional[Union[HTTPRequestsConnectionClass, HTTPSRequestsConnectionClass]] = None,
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
return self.__check(*self.requestBlob(verb, url, parameters, headers, input, self.__customConnection(url)))
def graphql_query(self, query: str, variables: Dict[str, Any]) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
:calls: `POST /graphql `_
"""
input_ = {"query": query, "variables": {"input": variables}}
response_headers, data = self.requestJsonAndCheck("POST", self.graphql_url, input=input_)
if "errors" in data:
raise self.createException(400, response_headers, data)
return response_headers, data
def graphql_named_mutation(
self, mutation_name: str, variables: Dict[str, Any], output: Optional[str] = None
) -> Tuple[Dict[str, Any], Dict[str, Any]]:
"""
Create a mutation in the format:
mutation MutationName($input: MutationNameInput!) {
mutationName(input: $input) {