| 1 |
#!/usr/bin/python |
| 2 |
# -*- coding: utf-8 -*- |
| 3 |
|
| 4 |
# Copyright (c) 2018, KubeVirt Team <@kubevirt> |
| 5 |
# GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) |
| 6 |
|
| 7 |
from __future__ import absolute_import, division, print_function |
| 8 |
|
| 9 |
__metaclass__ = type |
| 10 |
|
| 11 |
DOCUMENTATION = r""" |
| 12 |
|
| 13 |
module: openshift_auth |
| 14 |
|
| 15 |
short_description: Authenticate to OpenShift clusters which require an explicit login step |
| 16 |
|
| 17 |
version_added: "0.2.0" |
| 18 |
|
| 19 |
author: |
| 20 |
- KubeVirt Team (@kubevirt) |
| 21 |
- Fabian von Feilitzsch (@fabianvf) |
| 22 |
|
| 23 |
description: |
| 24 |
- This module handles authenticating to OpenShift clusters requiring I(explicit) authentication procedures, |
| 25 |
meaning ones where a client logs in (obtains an authentication token), performs API operations using said |
| 26 |
token and then logs out (revokes the token). |
| 27 |
- On the other hand a popular configuration for username+password authentication is one utilizing HTTP Basic |
| 28 |
Auth, which does not involve any additional login/logout steps (instead login credentials can be attached |
| 29 |
to each and every API call performed) and as such is handled directly by the C(k8s) module (and other |
| 30 |
resource–specific modules) by utilizing the C(host), C(username) and C(password) parameters. Please |
| 31 |
consult your preferred module's documentation for more details. |
| 32 |
|
| 33 |
options: |
| 34 |
state: |
| 35 |
description: |
| 36 |
- If set to I(present) connect to the API server using the URL specified in C(host) and attempt to log in. |
| 37 |
- If set to I(absent) attempt to log out by revoking the authentication token specified in C(api_key). |
| 38 |
default: present |
| 39 |
choices: |
| 40 |
- present |
| 41 |
- absent |
| 42 |
type: str |
| 43 |
host: |
| 44 |
description: |
| 45 |
- Provide a URL for accessing the API server. |
| 46 |
required: true |
| 47 |
type: str |
| 48 |
username: |
| 49 |
description: |
| 50 |
- Provide a username for authenticating with the API server. |
| 51 |
type: str |
| 52 |
password: |
| 53 |
description: |
| 54 |
- Provide a password for authenticating with the API server. |
| 55 |
type: str |
| 56 |
ca_cert: |
| 57 |
description: |
| 58 |
- "Path to a CA certificate file used to verify connection to the API server. The full certificate chain |
| 59 |
must be provided to avoid certificate validation errors." |
| 60 |
aliases: [ ssl_ca_cert ] |
| 61 |
type: path |
| 62 |
validate_certs: |
| 63 |
description: |
| 64 |
- "Whether or not to verify the API server's SSL certificates." |
| 65 |
type: bool |
| 66 |
default: true |
| 67 |
aliases: [ verify_ssl ] |
| 68 |
api_key: |
| 69 |
description: |
| 70 |
- When C(state) is set to I(absent), this specifies the token to revoke. |
| 71 |
type: str |
| 72 |
|
| 73 |
requirements: |
| 74 |
- python >= 3.6 |
| 75 |
- urllib3 |
| 76 |
- requests |
| 77 |
- requests-oauthlib |
| 78 |
""" |
| 79 |
|
| 80 |
EXAMPLES = r""" |
| 81 |
- name: Example Playbook |
| 82 |
hosts: localhost |
| 83 |
module_defaults: |
| 84 |
group/community.okd.okd: |
| 85 |
host: https://k8s.example.com/ |
| 86 |
ca_cert: ca.pem |
| 87 |
tasks: |
| 88 |
- name: Authenticate to OpenShift cluster and gell a list of all pods from any namespace |
| 89 |
block: |
| 90 |
# It's good practice to store login credentials in a secure vault and not |
| 91 |
# directly in playbooks. |
| 92 |
- name: Include 'openshift_passwords.yml' |
| 93 |
ansible.builtin.include_vars: openshift_passwords.yml |
| 94 |
|
| 95 |
- name: Log in (obtain access token) |
| 96 |
community.okd.openshift_auth: |
| 97 |
username: admin |
| 98 |
password: "{{ openshift_admin_password }}" |
| 99 |
register: openshift_auth_results |
| 100 |
|
| 101 |
# Previous task provides the token/api_key, while all other parameters |
| 102 |
# are taken from module_defaults |
| 103 |
- name: Get a list of all pods from any namespace |
| 104 |
kubernetes.core.k8s_info: |
| 105 |
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}" |
| 106 |
kind: Pod |
| 107 |
register: pod_list |
| 108 |
|
| 109 |
always: |
| 110 |
- name: If login succeeded, try to log out (revoke access token) |
| 111 |
when: openshift_auth_results.openshift_auth.api_key is defined |
| 112 |
community.okd.openshift_auth: |
| 113 |
state: absent |
| 114 |
api_key: "{{ openshift_auth_results.openshift_auth.api_key }}" |
| 115 |
""" |
| 116 |
|
| 117 |
# Returned value names need to match k8s modules parameter names, to make it |
| 118 |
# easy to pass returned values of openshift_auth to other k8s modules. |
| 119 |
# Discussion: https://github.com/ansible/ansible/pull/50807#discussion_r248827899 |
| 120 |
RETURN = r""" |
| 121 |
openshift_auth: |
| 122 |
description: OpenShift authentication facts. |
| 123 |
returned: success |
| 124 |
type: complex |
| 125 |
contains: |
| 126 |
api_key: |
| 127 |
description: Authentication token. |
| 128 |
returned: success |
| 129 |
type: str |
| 130 |
host: |
| 131 |
description: URL for accessing the API server. |
| 132 |
returned: success |
| 133 |
type: str |
| 134 |
ca_cert: |
| 135 |
description: Path to a CA certificate file used to verify connection to the API server. |
| 136 |
returned: success |
| 137 |
type: str |
| 138 |
validate_certs: |
| 139 |
description: "Whether or not to verify the API server's SSL certificates." |
| 140 |
returned: success |
| 141 |
type: bool |
| 142 |
username: |
| 143 |
description: Username for authenticating with the API server. |
| 144 |
returned: success |
| 145 |
type: str |
| 146 |
k8s_auth: |
| 147 |
description: Same as returned openshift_auth. Kept only for backwards compatibility |
| 148 |
returned: success |
| 149 |
type: complex |
| 150 |
contains: |
| 151 |
api_key: |
| 152 |
description: Authentication token. |
| 153 |
returned: success |
| 154 |
type: str |
| 155 |
host: |
| 156 |
description: URL for accessing the API server. |
| 157 |
returned: success |
| 158 |
type: str |
| 159 |
ca_cert: |
| 160 |
description: Path to a CA certificate file used to verify connection to the API server. |
| 161 |
returned: success |
| 162 |
type: str |
| 163 |
validate_certs: |
| 164 |
description: "Whether or not to verify the API server's SSL certificates." |
| 165 |
returned: success |
| 166 |
type: bool |
| 167 |
username: |
| 168 |
description: Username for authenticating with the API server. |
| 169 |
returned: success |
| 170 |
type: str |
| 171 |
""" |
| 172 |
|
| 173 |
|
| 174 |
import traceback |
| 175 |
|
| 176 |
from ansible.module_utils.basic import AnsibleModule |
| 177 |
from ansible.module_utils.six.moves.urllib_parse import urlparse, parse_qs, urlencode |
| 178 |
from urllib.parse import urljoin |
| 179 |
|
| 180 |
from base64 import urlsafe_b64encode |
| 181 |
import hashlib |
| 182 |
|
| 183 |
# 3rd party imports |
| 184 |
try: |
| 185 |
import requests |
| 186 |
|
| 187 |
HAS_REQUESTS = True |
| 188 |
except ImportError: |
| 189 |
HAS_REQUESTS = False |
| 190 |
|
| 191 |
try: |
| 192 |
from requests_oauthlib import OAuth2Session |
| 193 |
|
| 194 |
HAS_REQUESTS_OAUTH = True |
| 195 |
except ImportError: |
| 196 |
HAS_REQUESTS_OAUTH = False |
| 197 |
|
| 198 |
try: |
| 199 |
from urllib3.util import make_headers |
| 200 |
|
| 201 |
HAS_URLLIB3 = True |
| 202 |
except ImportError: |
| 203 |
HAS_URLLIB3 = False |
| 204 |
|
| 205 |
|
| 206 |
K8S_AUTH_ARG_SPEC = { |
| 207 |
"state": { |
| 208 |
"default": "present", |
| 209 |
"choices": ["present", "absent"], |
| 210 |
}, |
| 211 |
"host": {"required": True}, |
| 212 |
"username": {}, |
| 213 |
"password": {"no_log": True}, |
| 214 |
"ca_cert": {"type": "path", "aliases": ["ssl_ca_cert"]}, |
| 215 |
"validate_certs": {"type": "bool", "default": True, "aliases": ["verify_ssl"]}, |
| 216 |
"api_key": {"no_log": True}, |
| 217 |
} |
| 218 |
|
| 219 |
|
| 220 |
def get_oauthaccesstoken_objectname_from_token(token_name): |
| 221 |
""" |
| 222 |
openshift convert the access token to an OAuthAccessToken resource name using the algorithm |
| 223 |
https://github.com/openshift/console/blob/9f352ba49f82ad693a72d0d35709961428b43b93/pkg/server/server.go#L609-L613 |
| 224 |
""" |
| 225 |
|
| 226 |
sha256Prefix = "sha256~" |
| 227 |
if token_name.startswith(sha256Prefix): |
| 228 |
content = token_name[len(sha256Prefix) :] |
| 229 |
else: |
| 230 |
content = token_name |
| 231 |
b64encoded = urlsafe_b64encode(hashlib.sha256(content.encode()).digest()).rstrip( |
| 232 |
b"=" |
| 233 |
) |
| 234 |
return sha256Prefix + b64encoded.decode("utf-8") |
| 235 |
|
| 236 |
|
| 237 |
class OpenShiftAuthModule(AnsibleModule): |
| 238 |
def __init__(self): |
| 239 |
AnsibleModule.__init__( |
| 240 |
self, |
| 241 |
argument_spec=K8S_AUTH_ARG_SPEC, |
| 242 |
required_if=[ |
| 243 |
("state", "present", ["username", "password"]), |
| 244 |
("state", "absent", ["api_key"]), |
| 245 |
], |
| 246 |
) |
| 247 |
|
| 248 |
if not HAS_REQUESTS: |
| 249 |
self.fail( |
| 250 |
"This module requires the python 'requests' package. Try `pip install requests`." |
| 251 |
) |
| 252 |
|
| 253 |
if not HAS_REQUESTS_OAUTH: |
| 254 |
self.fail( |
| 255 |
"This module requires the python 'requests-oauthlib' package. Try `pip install requests-oauthlib`." |
| 256 |
) |
| 257 |
|
| 258 |
if not HAS_URLLIB3: |
| 259 |
self.fail( |
| 260 |
"This module requires the python 'urllib3' package. Try `pip install urllib3`." |
| 261 |
) |
| 262 |
|
| 263 |
def execute_module(self): |
| 264 |
state = self.params.get("state") |
| 265 |
verify_ssl = self.params.get("validate_certs") |
| 266 |
ssl_ca_cert = self.params.get("ca_cert") |
| 267 |
|
| 268 |
self.auth_username = self.params.get("username") |
| 269 |
self.auth_password = self.params.get("password") |
| 270 |
self.auth_api_key = self.params.get("api_key") |
| 271 |
self.con_host = self.params.get("host") |
| 272 |
|
| 273 |
# python-requests takes either a bool or a path to a ca file as the 'verify' param |
| 274 |
if verify_ssl and ssl_ca_cert: |
| 275 |
self.con_verify_ca = ssl_ca_cert # path |
| 276 |
else: |
| 277 |
self.con_verify_ca = verify_ssl # bool |
| 278 |
|
| 279 |
# Get needed info to access authorization APIs |
| 280 |
self.openshift_discover() |
| 281 |
|
| 282 |
changed = False |
| 283 |
result = dict() |
| 284 |
if state == "present": |
| 285 |
new_api_key = self.openshift_login() |
| 286 |
result = dict( |
| 287 |
host=self.con_host, |
| 288 |
validate_certs=verify_ssl, |
| 289 |
ca_cert=ssl_ca_cert, |
| 290 |
api_key=new_api_key, |
| 291 |
username=self.auth_username, |
| 292 |
) |
| 293 |
else: |
| 294 |
changed = self.openshift_logout() |
| 295 |
|
| 296 |
# return k8s_auth as well for backwards compatibility |
| 297 |
self.exit_json(changed=changed, openshift_auth=result, k8s_auth=result) |
| 298 |
|
| 299 |
def openshift_discover(self): |
| 300 |
url = urljoin(self.con_host, ".well-known/oauth-authorization-server") |
| 301 |
ret = requests.get(url, verify=self.con_verify_ca) |
| 302 |
|
| 303 |
if ret.status_code != 200: |
| 304 |
self.fail_request( |
| 305 |
"Couldn't find OpenShift's OAuth API", |
| 306 |
method="GET", |
| 307 |
url=url, |
| 308 |
reason=ret.reason, |
| 309 |
status_code=ret.status_code, |
| 310 |
) |
| 311 |
|
| 312 |
try: |
| 313 |
oauth_info = ret.json() |
| 314 |
|
| 315 |
self.openshift_auth_endpoint = oauth_info["authorization_endpoint"] |
| 316 |
self.openshift_token_endpoint = oauth_info["token_endpoint"] |
| 317 |
except Exception: |
| 318 |
self.fail_json( |
| 319 |
msg="Something went wrong discovering OpenShift OAuth details.", |
| 320 |
exception=traceback.format_exc(), |
| 321 |
) |
| 322 |
|
| 323 |
def openshift_login(self): |
| 324 |
os_oauth = OAuth2Session(client_id="openshift-challenging-client") |
| 325 |
authorization_url, state = os_oauth.authorization_url( |
| 326 |
self.openshift_auth_endpoint, state="1", code_challenge_method="S256" |
| 327 |
) |
| 328 |
auth_headers = make_headers( |
| 329 |
basic_auth="{0}:{1}".format(self.auth_username, self.auth_password) |
| 330 |
) |
| 331 |
|
| 332 |
# Request authorization code using basic auth credentials |
| 333 |
ret = os_oauth.get( |
| 334 |
authorization_url, |
| 335 |
headers={ |
| 336 |
"X-Csrf-Token": state, |
| 337 |
"authorization": auth_headers.get("authorization"), |
| 338 |
}, |
| 339 |
verify=self.con_verify_ca, |
| 340 |
allow_redirects=False, |
| 341 |
) |
| 342 |
|
| 343 |
if ret.status_code != 302: |
| 344 |
self.fail_request( |
| 345 |
"Authorization failed.", |
| 346 |
method="GET", |
| 347 |
url=authorization_url, |
| 348 |
reason=ret.reason, |
| 349 |
status_code=ret.status_code, |
| 350 |
) |
| 351 |
|
| 352 |
# In here we have `code` and `state`, I think `code` is the important one |
| 353 |
qwargs = {} |
| 354 |
for k, v in parse_qs(urlparse(ret.headers["Location"]).query).items(): |
| 355 |
qwargs[k] = v[0] |
| 356 |
qwargs["grant_type"] = "authorization_code" |
| 357 |
|
| 358 |
# Using authorization code given to us in the Location header of the previous request, request a token |
| 359 |
ret = os_oauth.post( |
| 360 |
self.openshift_token_endpoint, |
| 361 |
headers={ |
| 362 |
"Accept": "application/json", |
| 363 |
"Content-Type": "application/x-www-form-urlencoded", |
| 364 |
# This is just base64 encoded 'openshift-challenging-client:' |
| 365 |
"Authorization": "Basic b3BlbnNoaWZ0LWNoYWxsZW5naW5nLWNsaWVudDo=", |
| 366 |
}, |
| 367 |
data=urlencode(qwargs), |
| 368 |
verify=self.con_verify_ca, |
| 369 |
) |
| 370 |
|
| 371 |
if ret.status_code != 200: |
| 372 |
self.fail_request( |
| 373 |
"Failed to obtain an authorization token.", |
| 374 |
method="POST", |
| 375 |
url=self.openshift_token_endpoint, |
| 376 |
reason=ret.reason, |
| 377 |
status_code=ret.status_code, |
| 378 |
) |
| 379 |
|
| 380 |
return ret.json()["access_token"] |
| 381 |
|
| 382 |
def openshift_logout(self): |
| 383 |
name = get_oauthaccesstoken_objectname_from_token(self.auth_api_key) |
| 384 |
headers = { |
| 385 |
"Accept": "application/json", |
| 386 |
"Content-Type": "application/json", |
| 387 |
"Authorization": "Bearer {0}".format(self.auth_api_key), |
| 388 |
} |
| 389 |
|
| 390 |
url = "{0}/apis/oauth.openshift.io/v1/useroauthaccesstokens/{1}".format( |
| 391 |
self.con_host, name |
| 392 |
) |
| 393 |
json = { |
| 394 |
"apiVersion": "oauth.openshift.io/v1", |
| 395 |
"kind": "DeleteOptions", |
| 396 |
"gracePeriodSeconds": 0, |
| 397 |
} |
| 398 |
|
| 399 |
ret = requests.delete( |
| 400 |
url, json=json, verify=self.con_verify_ca, headers=headers |
| 401 |
) |
| 402 |
if ret.status_code != 200: |
| 403 |
self.fail_json( |
| 404 |
msg="Couldn't delete user oauth access token '{0}' due to: {1}".format( |
| 405 |
name, ret.json().get("message") |
| 406 |
), |
| 407 |
status_code=ret.status_code, |
| 408 |
) |
| 409 |
|
| 410 |
return True |
| 411 |
|
| 412 |
def fail(self, msg=None): |
| 413 |
self.fail_json(msg=msg) |
| 414 |
|
| 415 |
def fail_request(self, msg, **kwargs): |
| 416 |
req_info = {} |
| 417 |
for k, v in kwargs.items(): |
| 418 |
req_info["req_" + k] = v |
| 419 |
self.fail_json(msg=msg, **req_info) |
| 420 |
|
| 421 |
|
| 422 |
def main(): |
| 423 |
module = OpenShiftAuthModule() |
| 424 |
try: |
| 425 |
module.execute_module() |
| 426 |
except Exception as e: |
| 427 |
module.fail_json(msg=str(e), exception=traceback.format_exc()) |
| 428 |
|
| 429 |
|
| 430 |
if __name__ == "__main__": |
| 431 |
main() |