| 1 |
# Copyright (c) 2023, Poh Wei Sheng <[email protected]> |
| 2 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 3 |
# SPDX-License-Identifier: GPL-3.0-or-later |
| 4 |
from __future__ import annotations |
| 5 |
|
| 6 |
DOCUMENTATION = r""" |
| 7 |
name: github_app_access_token |
| 8 |
author: |
| 9 |
- Poh Wei Sheng (@weisheng-p) |
| 10 |
- Bruno Lavoie (@blavoie) |
| 11 |
short_description: Obtain short-lived Github App Access tokens |
| 12 |
version_added: '8.2.0' |
| 13 |
requirements: |
| 14 |
- jwt (https://github.com/GehirnInc/python-jwt) OR |
| 15 |
- PyJWT (https://pypi.org/project/PyJWT/) AND cryptography (https://pypi.org/project/cryptography/) |
| 16 |
description: |
| 17 |
- This generates a Github access token that can be used with a C(git) command, if you use a Github App. |
| 18 |
options: |
| 19 |
key_path: |
| 20 |
description: |
| 21 |
- Path to your private key. |
| 22 |
- Either O(key_path) or O(private_key) must be specified. |
| 23 |
type: path |
| 24 |
app_id: |
| 25 |
description: |
| 26 |
- Your GitHub App ID, you can find this in the Settings page. |
| 27 |
required: true |
| 28 |
type: str |
| 29 |
installation_id: |
| 30 |
description: |
| 31 |
- The installation ID that contains the git repository you would like access to. |
| 32 |
- As of 2023-12-24, this can be found at Settings page > Integrations > Application. The last part of the URL in the |
| 33 |
configure button is the installation ID. |
| 34 |
- Alternatively, you can use PyGithub (U(https://github.com/PyGithub/PyGithub)) to get your installation ID. |
| 35 |
required: true |
| 36 |
type: str |
| 37 |
private_key: |
| 38 |
description: |
| 39 |
- GitHub App private key in PEM file format as string. |
| 40 |
- Either O(key_path) or O(private_key) must be specified. |
| 41 |
type: str |
| 42 |
version_added: 10.0.0 |
| 43 |
token_expiry: |
| 44 |
description: |
| 45 |
- How long the token should last for in seconds. |
| 46 |
default: 600 |
| 47 |
type: int |
| 48 |
github_url: |
| 49 |
description: |
| 50 |
- Base URL for the GitHub API (for GitHub Enterprise Server). |
| 51 |
- "Example: C(https://github-enterprise-server.example.com/api/v3)" |
| 52 |
default: https://api.github.com |
| 53 |
type: str |
| 54 |
version_added: 11.4.0 |
| 55 |
""" |
| 56 |
|
| 57 |
EXAMPLES = r""" |
| 58 |
- name: Get access token to be used for git checkout with app_id=123456, installation_id=64209 |
| 59 |
ansible.builtin.git: |
| 60 |
repo: >- |
| 61 |
https://x-access-token:{{ github_token }}@github.com/hidden_user/super-secret-repo.git |
| 62 |
dest: /srv/checkout |
| 63 |
vars: |
| 64 |
github_token: >- |
| 65 |
{{ lookup('community.general.github_app_access_token', key_path='/home/to_your/key', |
| 66 |
app_id='123456', installation_id='64209') }} |
| 67 |
""" |
| 68 |
|
| 69 |
RETURN = r""" |
| 70 |
_raw: |
| 71 |
description: A one-element list containing your GitHub access token. |
| 72 |
type: list |
| 73 |
elements: str |
| 74 |
""" |
| 75 |
|
| 76 |
try: |
| 77 |
import jwt |
| 78 |
|
| 79 |
HAS_JWT = True |
| 80 |
except ImportError: |
| 81 |
HAS_JWT = False |
| 82 |
|
| 83 |
HAS_PYTHON_JWT = False # vs pyjwt |
| 84 |
if HAS_JWT and hasattr(jwt, "JWT"): |
| 85 |
HAS_PYTHON_JWT = True |
| 86 |
from jwt import JWT, jwk_from_pem # type: ignore[attr-defined] |
| 87 |
|
| 88 |
jwt_instance = JWT() |
| 89 |
|
| 90 |
try: |
| 91 |
from cryptography.hazmat.primitives import serialization |
| 92 |
|
| 93 |
HAS_CRYPTOGRAPHY = True |
| 94 |
except ImportError: |
| 95 |
HAS_CRYPTOGRAPHY = False |
| 96 |
|
| 97 |
|
| 98 |
import json |
| 99 |
import time |
| 100 |
from http import HTTPStatus |
| 101 |
from urllib.error import HTTPError |
| 102 |
|
| 103 |
from ansible.errors import AnsibleError, AnsibleOptionsError |
| 104 |
from ansible.module_utils.urls import open_url |
| 105 |
from ansible.plugins.lookup import LookupBase |
| 106 |
from ansible.utils.display import Display |
| 107 |
|
| 108 |
from ansible_collections.community.general.plugins.plugin_utils._lookup import check_for_no_terms |
| 109 |
|
| 110 |
display = Display() |
| 111 |
|
| 112 |
|
| 113 |
class PythonJWT: |
| 114 |
@staticmethod |
| 115 |
def read_key(path, private_key=None): |
| 116 |
try: |
| 117 |
if private_key: |
| 118 |
return jwk_from_pem(private_key.encode("utf-8")) |
| 119 |
with open(path, "rb") as pem_file: |
| 120 |
return jwk_from_pem(pem_file.read()) |
| 121 |
except Exception as e: |
| 122 |
raise AnsibleError(f"Error while parsing key file: {e}") from e |
| 123 |
|
| 124 |
@staticmethod |
| 125 |
def encode_jwt(app_id, jwk, exp=600): |
| 126 |
now = int(time.time()) |
| 127 |
payload = { |
| 128 |
"iat": now, |
| 129 |
"exp": now + exp, |
| 130 |
"iss": app_id, |
| 131 |
} |
| 132 |
try: |
| 133 |
return jwt_instance.encode(payload, jwk, alg="RS256") |
| 134 |
except Exception as e: |
| 135 |
raise AnsibleError(f"Error while encoding jwt: {e}") from e |
| 136 |
|
| 137 |
|
| 138 |
def read_key(path, private_key=None): |
| 139 |
if HAS_PYTHON_JWT: |
| 140 |
return PythonJWT.read_key(path, private_key) |
| 141 |
try: |
| 142 |
if private_key: |
| 143 |
key_bytes = private_key.encode("utf-8") |
| 144 |
else: |
| 145 |
with open(path, "rb") as pem_file: |
| 146 |
key_bytes = pem_file.read() |
| 147 |
return serialization.load_pem_private_key(key_bytes, password=None) |
| 148 |
except Exception as e: |
| 149 |
raise AnsibleError(f"Error while parsing key file: {e}") from e |
| 150 |
|
| 151 |
|
| 152 |
def encode_jwt(app_id, private_key_obj, exp=600): |
| 153 |
if HAS_PYTHON_JWT: |
| 154 |
return PythonJWT.encode_jwt(app_id, private_key_obj) |
| 155 |
now = int(time.time()) |
| 156 |
payload = { |
| 157 |
"iat": now, |
| 158 |
"exp": now + exp, |
| 159 |
"iss": app_id, |
| 160 |
} |
| 161 |
try: |
| 162 |
return jwt.encode(payload, private_key_obj, algorithm="RS256") |
| 163 |
except Exception as e: |
| 164 |
raise AnsibleError(f"Error while encoding jwt: {e}") from e |
| 165 |
|
| 166 |
|
| 167 |
def post_request(generated_jwt, installation_id, api_base): |
| 168 |
base = api_base.rstrip("/") |
| 169 |
github_url = f"{base}/app/installations/{installation_id}/access_tokens" |
| 170 |
|
| 171 |
headers = { |
| 172 |
"Authorization": f"Bearer {generated_jwt}", |
| 173 |
"Accept": "application/vnd.github.v3+json", |
| 174 |
} |
| 175 |
try: |
| 176 |
response = open_url(github_url, headers=headers, method="POST") |
| 177 |
except HTTPError as e: |
| 178 |
try: |
| 179 |
error_body = json.loads(e.read().decode()) |
| 180 |
display.vvv(f"Error returned: {error_body}") |
| 181 |
except Exception: |
| 182 |
error_body = {} |
| 183 |
if e.code == HTTPStatus.NOT_FOUND: |
| 184 |
raise AnsibleError("Github return error. Please confirm your installation_id value is valid") from e |
| 185 |
elif e.code == HTTPStatus.UNAUTHORIZED: |
| 186 |
raise AnsibleError("Github return error. Please confirm your private key is valid") from e |
| 187 |
raise AnsibleError(f"Unexpected data returned: {e} -- {error_body}") from e |
| 188 |
response_body = response.read() |
| 189 |
try: |
| 190 |
json_data = json.loads(response_body.decode("utf-8")) |
| 191 |
except json.decoder.JSONDecodeError as e: |
| 192 |
raise AnsibleError(f"Error while dencoding JSON respone from github: {e}") from e |
| 193 |
return json_data.get("token") |
| 194 |
|
| 195 |
|
| 196 |
def get_token(key_path, app_id, installation_id, private_key, github_url, expiry=600): |
| 197 |
jwk = read_key(key_path, private_key) |
| 198 |
generated_jwt = encode_jwt(app_id, jwk, exp=expiry) |
| 199 |
return post_request(generated_jwt, installation_id, github_url) |
| 200 |
|
| 201 |
|
| 202 |
class LookupModule(LookupBase): |
| 203 |
def run(self, terms, variables=None, **kwargs): |
| 204 |
if not HAS_JWT: |
| 205 |
raise AnsibleError('Python jwt library is required. Please install using "pip install pyjwt"') |
| 206 |
|
| 207 |
if not HAS_PYTHON_JWT and not HAS_CRYPTOGRAPHY: |
| 208 |
raise AnsibleError( |
| 209 |
'Python cryptography library is required. Please install using "pip install cryptography"' |
| 210 |
) |
| 211 |
|
| 212 |
self.set_options(var_options=variables, direct=kwargs) |
| 213 |
check_for_no_terms(self, terms=terms, direct=kwargs) |
| 214 |
|
| 215 |
if not (self.get_option("key_path") or self.get_option("private_key")): |
| 216 |
raise AnsibleOptionsError("One of key_path or private_key is required") |
| 217 |
if self.get_option("key_path") and self.get_option("private_key"): |
| 218 |
raise AnsibleOptionsError("key_path and private_key are mutually exclusive") |
| 219 |
|
| 220 |
t = get_token( |
| 221 |
self.get_option("key_path"), |
| 222 |
self.get_option("app_id"), |
| 223 |
self.get_option("installation_id"), |
| 224 |
self.get_option("private_key"), |
| 225 |
self.get_option("github_url"), |
| 226 |
self.get_option("token_expiry"), |
| 227 |
) |
| 228 |
|
| 229 |
return [t] |