| 1 |
######################################################################## |
| 2 |
# |
| 3 |
# (C) 2015, Chris Houseknecht <[email protected]> |
| 4 |
# |
| 5 |
# This file is part of Ansible |
| 6 |
# |
| 7 |
# Ansible is free software: you can redistribute it and/or modify |
| 8 |
# it under the terms of the GNU General Public License as published by |
| 9 |
# the Free Software Foundation, either version 3 of the License, or |
| 10 |
# (at your option) any later version. |
| 11 |
# |
| 12 |
# Ansible is distributed in the hope that it will be useful, |
| 13 |
# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 |
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 |
# GNU General Public License for more details. |
| 16 |
# |
| 17 |
# You should have received a copy of the GNU General Public License |
| 18 |
# along with Ansible. If not, see <http://www.gnu.org/licenses/>. |
| 19 |
# |
| 20 |
######################################################################## |
| 21 |
from __future__ import annotations |
| 22 |
|
| 23 |
import base64 |
| 24 |
import json |
| 25 |
import os |
| 26 |
import time |
| 27 |
from stat import S_IRUSR, S_IWUSR |
| 28 |
from urllib.error import HTTPError |
| 29 |
from urllib.parse import urlencode |
| 30 |
|
| 31 |
from ansible import constants as C |
| 32 |
from ansible.galaxy.api import GalaxyError |
| 33 |
from ansible.galaxy.user_agent import user_agent |
| 34 |
from ansible.module_utils.common.sentinel import Sentinel as NoTokenSentinel |
| 35 |
from ansible.module_utils.common.text.converters import to_bytes, to_native, to_text |
| 36 |
from ansible.module_utils.common.yaml import yaml_dump, yaml_load |
| 37 |
from ansible.module_utils.urls import open_url |
| 38 |
from ansible.utils.display import Display |
| 39 |
|
| 40 |
display = Display() |
| 41 |
|
| 42 |
|
| 43 |
class KeycloakToken(object): |
| 44 |
"""A token granted by a Keycloak server. |
| 45 |
|
| 46 |
Like sso.redhat.com as used by cloud.redhat.com |
| 47 |
ie Automation Hub""" |
| 48 |
|
| 49 |
token_type = 'Bearer' |
| 50 |
|
| 51 |
def __init__(self, access_token=None, auth_url=None, validate_certs=True, client_id=None, client_secret=None): |
| 52 |
self.access_token = access_token |
| 53 |
self.auth_url = auth_url |
| 54 |
self._token = None |
| 55 |
self.validate_certs = validate_certs |
| 56 |
self.client_id = client_id |
| 57 |
if self.client_id is None: |
| 58 |
self.client_id = 'cloud-services' |
| 59 |
self.client_secret = client_secret |
| 60 |
self._expiration = None |
| 61 |
|
| 62 |
def _form_payload(self): |
| 63 |
payload = { |
| 64 |
'client_id': self.client_id, |
| 65 |
} |
| 66 |
if self.client_secret: |
| 67 |
payload['client_secret'] = self.client_secret |
| 68 |
payload['scope'] = 'api.console' |
| 69 |
payload['grant_type'] = 'client_credentials' |
| 70 |
if self.access_token not in (None, NoTokenSentinel): |
| 71 |
display.warning( |
| 72 |
'Found both a client_secret and access_token for galaxy authentication, ignoring access_token' |
| 73 |
) |
| 74 |
else: |
| 75 |
payload['refresh_token'] = self.access_token |
| 76 |
payload['grant_type'] = 'refresh_token' |
| 77 |
|
| 78 |
return urlencode(payload) |
| 79 |
|
| 80 |
def get(self): |
| 81 |
if self._expiration and time.time() >= self._expiration: |
| 82 |
self._token = None |
| 83 |
|
| 84 |
if self._token: |
| 85 |
return self._token |
| 86 |
|
| 87 |
payload = self._form_payload() |
| 88 |
|
| 89 |
display.vvv(f'Authenticating via {self.auth_url}') |
| 90 |
try: |
| 91 |
resp = open_url(to_native(self.auth_url), |
| 92 |
data=payload, |
| 93 |
validate_certs=self.validate_certs, |
| 94 |
method='POST', |
| 95 |
http_agent=user_agent()) |
| 96 |
except HTTPError as e: |
| 97 |
raise GalaxyError(e, 'Unable to get access token') |
| 98 |
display.vvv('Authentication successful') |
| 99 |
|
| 100 |
data = json.load(resp) |
| 101 |
|
| 102 |
# So that we have a buffer, expire the token in ~2/3 the given value |
| 103 |
expires_in = data['expires_in'] // 3 * 2 |
| 104 |
self._expiration = time.time() + expires_in |
| 105 |
display.vvv(f'Authentication token expires in {expires_in} seconds') |
| 106 |
|
| 107 |
self._token = data.get('access_token') |
| 108 |
if token_type := data.get('token_type'): |
| 109 |
self.token_type = token_type |
| 110 |
|
| 111 |
return self._token |
| 112 |
|
| 113 |
def headers(self): |
| 114 |
headers = {} |
| 115 |
headers['Authorization'] = '%s %s' % (self.token_type, self.get()) |
| 116 |
return headers |
| 117 |
|
| 118 |
|
| 119 |
class GalaxyToken(object): |
| 120 |
""" Class to storing and retrieving local galaxy token """ |
| 121 |
|
| 122 |
token_type = 'Token' |
| 123 |
|
| 124 |
def __init__(self, token=None): |
| 125 |
self.b_file = to_bytes(C.GALAXY_TOKEN_PATH, errors='surrogate_or_strict') |
| 126 |
# Done so the config file is only opened when set/get/save is called |
| 127 |
self._config = None |
| 128 |
self._token = token |
| 129 |
|
| 130 |
@property |
| 131 |
def config(self): |
| 132 |
if self._config is None: |
| 133 |
self._config = self._read() |
| 134 |
|
| 135 |
# Prioritise the token passed into the constructor |
| 136 |
if self._token: |
| 137 |
self._config['token'] = None if self._token is NoTokenSentinel else self._token |
| 138 |
|
| 139 |
return self._config |
| 140 |
|
| 141 |
def _read(self): |
| 142 |
action = 'Opened' |
| 143 |
if not os.path.isfile(self.b_file): |
| 144 |
# token file not found, create and chmod u+rw |
| 145 |
open(self.b_file, 'w').close() |
| 146 |
os.chmod(self.b_file, S_IRUSR | S_IWUSR) # owner has +rw |
| 147 |
action = 'Created' |
| 148 |
|
| 149 |
with open(self.b_file, 'r') as f: |
| 150 |
config = yaml_load(f) |
| 151 |
|
| 152 |
display.vvv('%s %s' % (action, to_text(self.b_file))) |
| 153 |
|
| 154 |
if config and not isinstance(config, dict): |
| 155 |
display.vvv('Galaxy token file %s malformed, unable to read it' % to_text(self.b_file)) |
| 156 |
return {} |
| 157 |
|
| 158 |
return config or {} |
| 159 |
|
| 160 |
def set(self, token): |
| 161 |
self._token = token |
| 162 |
self.save() |
| 163 |
|
| 164 |
def get(self): |
| 165 |
return self.config.get('token', None) |
| 166 |
|
| 167 |
def save(self): |
| 168 |
with open(self.b_file, 'w') as f: |
| 169 |
yaml_dump(self.config, f, default_flow_style=False) |
| 170 |
|
| 171 |
def headers(self): |
| 172 |
headers = {} |
| 173 |
token = self.get() |
| 174 |
if token: |
| 175 |
headers['Authorization'] = '%s %s' % (self.token_type, self.get()) |
| 176 |
return headers |
| 177 |
|
| 178 |
|
| 179 |
class BasicAuthToken(object): |
| 180 |
token_type = 'Basic' |
| 181 |
|
| 182 |
def __init__(self, username, password=None): |
| 183 |
self.username = username |
| 184 |
self.password = password |
| 185 |
self._token = None |
| 186 |
|
| 187 |
@staticmethod |
| 188 |
def _encode_token(username, password): |
| 189 |
token = "%s:%s" % (to_text(username, errors='surrogate_or_strict'), |
| 190 |
to_text(password, errors='surrogate_or_strict', nonstring='passthru') or '') |
| 191 |
b64_val = base64.b64encode(to_bytes(token, encoding='utf-8', errors='surrogate_or_strict')) |
| 192 |
return to_text(b64_val) |
| 193 |
|
| 194 |
def get(self): |
| 195 |
if self._token: |
| 196 |
return self._token |
| 197 |
|
| 198 |
self._token = self._encode_token(self.username, self.password) |
| 199 |
|
| 200 |
return self._token |
| 201 |
|
| 202 |
def headers(self): |
| 203 |
headers = {} |
| 204 |
headers['Authorization'] = '%s %s' % (self.token_type, self.get()) |
| 205 |
return headers |