
    Vhf6              	       h   d dl mZmZmZ eZdZdZdZd dl	Z	d dl
mZ d dlmZmZmZ d dlmZ d d	lmZ d dlZ	 d dlZd
Z	 d dlmZ d
Z	 d dlmZ d
Zdddgddd
ii dd
iddgddd
dgddd
idZd Z G d de      Z d Z!e"dk(  r e!        yy# e$ r dZY Xw xY w# e$ r dZY \w xY w# e$ r dZY `w xY w)    )absolute_importdivisionprint_functionu  

module: openshift_auth

short_description: Authenticate to OpenShift clusters which require an explicit login step

version_added: "0.2.0"

author:
  - KubeVirt Team (@kubevirt)
  - Fabian von Feilitzsch (@fabianvf)

description:
  - This module handles authenticating to OpenShift clusters requiring I(explicit) authentication procedures,
    meaning ones where a client logs in (obtains an authentication token), performs API operations using said
    token and then logs out (revokes the token).
  - On the other hand a popular configuration for username+password authentication is one utilizing HTTP Basic
    Auth, which does not involve any additional login/logout steps (instead login credentials can be attached
    to each and every API call performed) and as such is handled directly by the C(k8s) module (and other
    resource–specific modules) by utilizing the C(host), C(username) and C(password) parameters. Please
    consult your preferred module's documentation for more details.

options:
  state:
    description:
    - If set to I(present) connect to the API server using the URL specified in C(host) and attempt to log in.
    - If set to I(absent) attempt to log out by revoking the authentication token specified in C(api_key).
    default: present
    choices:
    - present
    - absent
    type: str
  host:
    description:
    - Provide a URL for accessing the API server.
    required: true
    type: str
  username:
    description:
    - Provide a username for authenticating with the API server.
    type: str
  password:
    description:
    - Provide a password for authenticating with the API server.
    type: str
  ca_cert:
    description:
    - "Path to a CA certificate file used to verify connection to the API server. The full certificate chain
      must be provided to avoid certificate validation errors."
    aliases: [ ssl_ca_cert ]
    type: path
  validate_certs:
    description:
    - "Whether or not to verify the API server's SSL certificates."
    type: bool
    default: true
    aliases: [ verify_ssl ]
  api_key:
    description:
    - When C(state) is set to I(absent), this specifies the token to revoke.
    type: str

requirements:
  - python >= 3.6
  - urllib3
  - requests
  - requests-oauthlib
aG  
- name: Example Playbook
  hosts: localhost
  module_defaults:
    group/community.okd.okd:
      host: https://k8s.example.com/
      ca_cert: ca.pem
  tasks:
    - name: Authenticate to OpenShift cluster and gell a list of all pods from any namespace
      block:
        # It's good practice to store login credentials in a secure vault and not
        # directly in playbooks.
        - name: Include 'openshift_passwords.yml'
          ansible.builtin.include_vars: openshift_passwords.yml

        - name: Log in (obtain access token)
          community.okd.openshift_auth:
            username: admin
            password: "{{ openshift_admin_password }}"
          register: openshift_auth_results

        # Previous task provides the token/api_key, while all other parameters
        # are taken from module_defaults
        - name: Get a list of all pods from any namespace
          kubernetes.core.k8s_info:
            api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
            kind: Pod
          register: pod_list

      always:
        - name: If login succeeded, try to log out (revoke access token)
          when: openshift_auth_results.openshift_auth.api_key is defined
          community.okd.openshift_auth:
            state: absent
            api_key: "{{ openshift_auth_results.openshift_auth.api_key }}"
a  
openshift_auth:
  description: OpenShift authentication facts.
  returned: success
  type: complex
  contains:
    api_key:
      description: Authentication token.
      returned: success
      type: str
    host:
      description: URL for accessing the API server.
      returned: success
      type: str
    ca_cert:
      description: Path to a CA certificate file used to verify connection to the API server.
      returned: success
      type: str
    validate_certs:
      description: "Whether or not to verify the API server's SSL certificates."
      returned: success
      type: bool
    username:
      description: Username for authenticating with the API server.
      returned: success
      type: str
k8s_auth:
  description: Same as returned openshift_auth. Kept only for backwards compatibility
  returned: success
  type: complex
  contains:
    api_key:
      description: Authentication token.
      returned: success
      type: str
    host:
      description: URL for accessing the API server.
      returned: success
      type: str
    ca_cert:
      description: Path to a CA certificate file used to verify connection to the API server.
      returned: success
      type: str
    validate_certs:
      description: "Whether or not to verify the API server's SSL certificates."
      returned: success
      type: bool
    username:
      description: Username for authenticating with the API server.
      returned: success
      type: str
N)AnsibleModule)urlparseparse_qs	urlencode)urljoin)urlsafe_b64encodeTF)OAuth2Session)make_headerspresentabsent)defaultchoicesrequiredno_logpathssl_ca_cert)typealiasesbool
verify_ssl)r   r   r   )statehostusernamepasswordca_certvalidate_certsapi_keyc                    d}| j                  |      r| t        |      d }n| }t        t        j                  |j                               j                               j                  d      }||j                  d      z   S )z
    openshift convert the access token to an OAuthAccessToken resource name using the algorithm
    https://github.com/openshift/console/blob/9f352ba49f82ad693a72d0d35709961428b43b93/pkg/server/server.go#L609-L613
    zsha256~N   =zutf-8)	
startswithlenr   hashlibsha256encodedigestrstripdecode)
token_namesha256Prefixcontent
b64encodeds       p/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/okd/plugins/modules/openshift_auth.py*get_oauthaccesstoken_objectname_from_tokenr0      sw     L\*S.01"7>>'..2B#C#J#J#LMTTJ *++G444    c                   8    e Zd Zd Zd Zd Zd Zd Zd	dZd Z	y)
OpenShiftAuthModulec                     t        j                  | t        ddddgfdddgfg       t        s| j	                  d       t
        s| j	                  d	       t        s| j	                  d
       y y )Nr   r   r   r   r   r    )argument_specrequired_ifzOThis module requires the python 'requests' package. Try `pip install requests`.zaThis module requires the python 'requests-oauthlib' package. Try `pip install requests-oauthlib`.zMThis module requires the python 'urllib3' package. Try `pip install urllib3`.)r   __init__K8S_AUTH_ARG_SPECHAS_REQUESTSfailHAS_REQUESTS_OAUTHHAS_URLLIB3)selfs    r/   r7   zOpenShiftAuthModule.__init__   sw    +)j*%=>(YK0	
 IIa "IIs II_ r1   c                    | j                   j                  d      }| j                   j                  d      }| j                   j                  d      }| j                   j                  d      | _        | j                   j                  d      | _        | j                   j                  d      | _        | j                   j                  d      | _        |r
|r|| _        n|| _        | j                          d}t               }|d	k(  r5| j                         }t        | j
                  |||| j                  
      }n| j                         }| j                  |||       y )Nr   r   r   r   r   r    r   Fr   )r   r   r   r    r   )changedopenshift_authk8s_auth)paramsgetauth_usernameauth_passwordauth_api_keycon_hostcon_verify_caopenshift_discoverdictopenshift_loginopenshift_logout	exit_json)r=   r   r   r   r?   resultnew_api_keys          r/   execute_modulez"OpenShiftAuthModule.execute_module  s   ([[__%56
kkooi0![[__Z8![[__Z8 KKOOI6/ +!,D!+D 	!I..0K]])##++F ++-G 	wvOr1   c                    t        | j                  d      }t        j                  || j                        }|j
                  dk7  r*| j                  dd||j                  |j
                         	 |j                         }|d   | _	        |d   | _
        y # t        $ r( | j                  d	t        j                         
       Y y w xY w)Nz&.well-known/oauth-authorization-server)verify   z#Couldn't find OpenShift's OAuth APIGETmethodurlreasonstatus_codeauthorization_endpointtoken_endpointz9Something went wrong discovering OpenShift OAuth details.msg	exception)r
   rG   requestsrC   rH   rY   fail_requestrX   jsonopenshift_auth_endpointopenshift_token_endpoint	Exception	fail_json	traceback
format_exc)r=   rW   ret
oauth_infos       r/   rI   z&OpenShiftAuthModule.openshift_discover+  s    dmm%MNll3t'9'9:??c!5zzOO  		J+56N+OD(,67G,HD) 	NNO#..0  	s   2$B .CCc                 H   t        d      }|j                  | j                  dd      \  }}t        dj	                  | j
                  | j                              }|j                  |||j                  d      d	| j                  d
      }|j                  dk7  r*| j                  dd||j                  |j                         i }t        t        |j                  d         j                        j!                         D ]  \  }}|d   ||<    d|d<   |j#                  | j$                  ddddt'        |      | j                        }|j                  dk7  r4| j                  dd| j$                  |j                  |j                         |j)                         d   S )Nzopenshift-challenging-client)	client_id1S256)r   code_challenge_methodz{0}:{1})
basic_authauthorization)zX-Csrf-Tokenrp   F)headersrR   allow_redirectsi.  zAuthorization failed.rT   rU   Locationr   authorization_code
grant_typeapplication/jsonz!application/x-www-form-urlencodedz.Basic b3BlbnNoaWZ0LWNoYWxsZW5naW5nLWNsaWVudDo=AcceptzContent-TypeAuthorization)rq   datarR   rS   z(Failed to obtain an authorization token.POSTaccess_token)r   authorization_urlrb   r   formatrD   rE   rC   rH   rY   r`   rX   r   r   rq   queryitemspostrc   r	   ra   )	r=   os_oauthr}   r   auth_headersrh   qwargskvs	            r/   rK   z#OpenShiftAuthModule.openshift_loginC  s    +IJ#+#=#=((6 $> $
 5 $ ''(:(:D<N<NO

 ll %!-!1!1/!B %%!  
 ??c!'%zzOO   Xckk*&=>DDEKKM 	DAq!F1I	3| mm)), C!Q	 6"%%  

 ??c!:11zzOO   xxz.))r1   c                    t        | j                        }dddj                  | j                        d}dj                  | j                  |      }dddd}t	        j
                  ||| j                  |	      }|j                  d
k7  rJ| j                  dj                  ||j                         j                  d            |j                         y)Nrv   z
Bearer {0}rw   z8{0}/apis/oauth.openshift.io/v1/useroauthaccesstokens/{1}zoauth.openshift.io/v1DeleteOptionsr   )
apiVersionkindgracePeriodSeconds)ra   rR   rq   rS   z9Couldn't delete user oauth access token '{0}' due to: {1}message)r]   rY   T)r0   rF   r~   rG   r_   deleterH   rY   re   ra   rC   )r=   namerq   rW   ra   rh   s         r/   rL   z$OpenShiftAuthModule.openshift_logout~  s    9$:K:KL(.)001B1BC
 IOOMM4
 2#"#
 ood4#5#5w
 ??c!NNOVV#((*..3  OO	   r1   Nc                 (    | j                  |       y )N)r]   )re   )r=   r]   s     r/   r:   zOpenShiftAuthModule.fail  s    3r1   c                 p    i }|j                         D ]  \  }}||d|z   <     | j                  dd|i| y )Nreq_r]    )r   re   )r=   r]   kwargsreq_infor   r   s         r/   r`   z OpenShiftAuthModule.fail_request  sD    LLN 	%DAq#$HVaZ 	%+3+(+r1   )N)
__name__
__module____qualname__r7   rP   rI   rK   rL   r:   r`   r   r1   r/   r3   r3      s(    2"PH09*v< ,r1   r3   c                      t               } 	 | j                          y # t        $ r8}| j                  t	        |      t        j                                Y d }~y d }~ww xY w)Nr\   )r3   rP   rd   re   strrf   rg   )modulees     r/   mainr     sQ     "FG GSVy/C/C/EFFGs    	A.AA__main__)#
__future__r   r   r   r   __metaclass__DOCUMENTATIONEXAMPLESRETURNrf   ansible.module_utils.basicr   +ansible.module_utils.six.moves.urllib_parser   r   r	   urllib.parser
   base64r   r%   r_   r9   ImportErrorrequests_oauthlibr   r;   urllib3.utilr   r<   r8   r0   r3   r   r   r   r1   r/   <module>r      s(   A @CJ#P3
l  4 U U   $ L/)K x( 4 M?;%$L>R$ 5"v,- v,rG zF e  L    Ks4   B B B' BBB$#B$'B10B1