fastai / ghapi

A delightful and complete interface to GitHub's amazing API
https://ghapi.fast.ai/
Apache License 2.0
527 stars 57 forks source link

401: Unauthorized when calling apps.list_installations #85

Closed ghost closed 2 years ago

ghost commented 2 years ago

It looks like endpoints that require JWT tokens do not work.

I've verified the jwt token is valid by creating an access token via the github api.

Below is my code:

import time
import jwt

from ghapi.all import GhApi
import requests

private_key = """-----BEGIN RSA PRIVATE KEY-----"""
app_id = 1
installation_id = 1

def create_jwt(key, id, expiration=60):
    """
    Creates a signed JWT, valid for 60 seconds by default.
    The expiration can be extended beyond this, to a maximum of 600 seconds.
    :param expiration: int
    :return string:
    """
    now = int(time.time())
    payload = {"iat": now, "exp": now + expiration, "iss": id}
    encrypted = jwt.encode(payload, key=key, algorithm="RS256")

    if isinstance(encrypted, bytes):
        encrypted = encrypted.decode("utf-8")
    return encrypted

api = GhApi(token=create_jwt(key=private_key, id=app_id))

api.apps.list_installations()

returns

File "test.py", line 78, in <module>
    api.apps.list_installations()
  File "/usr/local/lib/python3.8/dist-packages/ghapi/core.py", line 63, in __call__
    return self.client(self.path, self.verb, headers=headers, route=route_p, query=query_p, data=data_p)
  File "/usr/local/lib/python3.8/dist-packages/ghapi/core.py", line 108, in __call__
    res,self.recv_hdrs = urlsend(path, verb, headers=headers or None, debug=self.debug, return_headers=True,
  File "/usr/local/lib/python3.8/dist-packages/fastcore/net.py", line 212, in urlsend
    return urlread(req, return_json=return_json, return_headers=return_headers)
  File "/usr/local/lib/python3.8/dist-packages/fastcore/net.py", line 113, in urlread
    if 400 <= e.code < 500: raise ExceptionsHTTP[e.code](e.url, e.hdrs, e.fp) from None
fastcore.basics.HTTP401UnauthorizedError: HTTP Error 401: Unauthorized
ghost commented 2 years ago

Looks like this is why jwt tokens do not work:

https://github.com/fastai/ghapi/blob/35347e9fdd08cbe970ca65e8074b0e6b8822ec58/ghapi/core.py#L90-L99

Github expects the header to have Bearer instead of token

"Authorization: Bearer YOUR_JWT"

Perhaps we can add a new attribute jwt_token. I know this package is auto generated from the API spec, but I'm assuming this part was manually written so it can be updated? I'll try this weekend.