
    Vh L                         d dl mZmZmZ eZdZdZdZd dl	m
Z
mZmZmZmZmZ d dlmZ ddZd Zd	 Zed
k(  r e        yy)    )absolute_importdivisionprint_functionud  
module: keycloak_clientscope

short_description: Allows administration of Keycloak client_scopes using Keycloak API

version_added: 3.4.0

description:
  - This module allows you to add, remove or modify Keycloak client_scopes using the Keycloak REST API. It requires access
    to the REST API using OpenID Connect; the user connecting and the client being used must have the requisite access rights.
    In a default Keycloak installation, admin-cli and an admin user would work, as would a separate client definition with
    the scope tailored to your needs and a user having the expected roles.
  - The names of module options are snake_cased versions of the camelCase ones found in the Keycloak API and its documentation
    at U(https://www.keycloak.org/docs-api/8.0/rest-api/index.html).
  - Attributes are multi-valued in the Keycloak API. All attributes are lists of individual values and will be returned that
    way by this module. You may pass single values for attributes when calling the module, and this will be translated into
    a list suitable for the API.
  - When updating a client_scope, where possible provide the client_scope ID to the module. This removes a lookup to the API
    to translate the name into the client_scope ID.
attributes:
  check_mode:
    support: full
  diff_mode:
    support: full
  action_group:
    version_added: 10.2.0

options:
  state:
    description:
      - State of the client_scope.
      - On V(present), the client_scope will be created if it does not yet exist, or updated with the parameters you provide.
      - On V(absent), the client_scope will be removed if it exists.
    default: 'present'
    type: str
    choices:
      - present
      - absent

  name:
    type: str
    description:
      - Name of the client_scope.
      - This parameter is required only when creating or updating the client_scope.
  realm:
    type: str
    description:
      - They Keycloak realm under which this client_scope resides.
    default: 'master'

  id:
    type: str
    description:
      - The unique identifier for this client_scope.
      - This parameter is not required for updating or deleting a client_scope but providing it will reduce the number of
        API calls required.
  description:
    type: str
    description:
      - Description for this client_scope.
      - This parameter is not required for updating or deleting a client_scope.
  protocol:
    description:
      - Type of client.
      - The V(docker-v2) value was added in community.general 8.6.0.
    choices: ['openid-connect', 'saml', 'wsfed', 'docker-v2']
    type: str

  protocol_mappers:
    description:
      - A list of dicts defining protocol mappers for this client.
      - This is C(protocolMappers) in the Keycloak REST API.
    aliases:
      - protocolMappers
    type: list
    elements: dict
    suboptions:
      protocol:
        description:
          - This specifies for which protocol this protocol mapper.
          - Is active.
        choices: ['openid-connect', 'saml', 'wsfed', 'docker-v2']
        type: str

      protocolMapper:
        description:
          - 'The Keycloak-internal name of the type of this protocol-mapper. While an exhaustive list is impossible to provide
            since this may be extended through SPIs by the user of Keycloak, by default Keycloak as of 3.4 ships with at least:'
          - V(docker-v2-allow-all-mapper).
          - V(oidc-address-mapper).
          - V(oidc-full-name-mapper).
          - V(oidc-group-membership-mapper).
          - V(oidc-hardcoded-claim-mapper).
          - V(oidc-hardcoded-role-mapper).
          - V(oidc-role-name-mapper).
          - V(oidc-script-based-protocol-mapper).
          - V(oidc-sha256-pairwise-sub-mapper).
          - V(oidc-usermodel-attribute-mapper).
          - V(oidc-usermodel-client-role-mapper).
          - V(oidc-usermodel-property-mapper).
          - V(oidc-usermodel-realm-role-mapper).
          - V(oidc-usersessionmodel-note-mapper).
          - V(saml-group-membership-mapper).
          - V(saml-hardcode-attribute-mapper).
          - V(saml-hardcode-role-mapper).
          - V(saml-role-list-mapper).
          - V(saml-role-name-mapper).
          - V(saml-user-attribute-mapper).
          - V(saml-user-property-mapper).
          - V(saml-user-session-note-mapper).
          - An exhaustive list of available mappers on your installation can be obtained on the admin console by going to
            Server Info -> Providers and looking under 'protocol-mapper'.
        type: str

      name:
        description:
          - The name of this protocol mapper.
        type: str

      id:
        description:
          - Usually a UUID specifying the internal ID of this protocol mapper instance.
        type: str

      config:
        description:
          - Dict specifying the configuration options for the protocol mapper; the contents differ depending on the value
            of O(protocol_mappers[].protocolMapper) and are not documented other than by the source of the mappers and its
            parent class(es). An example is given below. It is easiest to obtain valid config values by dumping an already-existing
            protocol mapper configuration through check-mode in the RV(existing) return value.
        type: dict

  attributes:
    type: dict
    description:
      - A dict of key/value pairs to set as custom attributes for the client_scope.
      - Values may be single values (for example a string) or a list of strings.
extends_documentation_fragment:
  - community.general.keycloak
  - community.general.keycloak.actiongroup_keycloak
  - community.general.attributes

author:
  - Gaëtan Daubresse (@Gaetan2907)
aR  
- name: Create a Keycloak client_scopes, authentication with credentials
  community.general.keycloak_clientscope:
    name: my-new-kc-clientscope
    realm: MyCustomRealm
    state: present
    auth_client_id: admin-cli
    auth_keycloak_url: https://auth.example.com/auth
    auth_realm: master
    auth_username: USERNAME
    auth_password: PASSWORD
  delegate_to: localhost

- name: Create a Keycloak client_scopes, authentication with token
  community.general.keycloak_clientscope:
    name: my-new-kc-clientscope
    realm: MyCustomRealm
    state: present
    auth_client_id: admin-cli
    auth_keycloak_url: https://auth.example.com/auth
    token: TOKEN
  delegate_to: localhost

- name: Delete a keycloak client_scopes
  community.general.keycloak_clientscope:
    id: '9d59aa76-2755-48c6-b1af-beb70a82c3cd'
    state: absent
    realm: MyCustomRealm
    auth_client_id: admin-cli
    auth_keycloak_url: https://auth.example.com/auth
    auth_realm: master
    auth_username: USERNAME
    auth_password: PASSWORD
  delegate_to: localhost

- name: Delete a Keycloak client_scope based on name
  community.general.keycloak_clientscope:
    name: my-clientscope-for-deletion
    state: absent
    auth_client_id: admin-cli
    auth_keycloak_url: https://auth.example.com/auth
    auth_realm: master
    auth_username: USERNAME
    auth_password: PASSWORD
  delegate_to: localhost

- name: Update the name of a Keycloak client_scope
  community.general.keycloak_clientscope:
    id: '9d59aa76-2755-48c6-b1af-beb70a82c3cd'
    name: an-updated-kc-clientscope-name
    state: present
    auth_client_id: admin-cli
    auth_keycloak_url: https://auth.example.com/auth
    auth_realm: master
    auth_username: USERNAME
    auth_password: PASSWORD
  delegate_to: localhost

- name: Create a Keycloak client_scope with some custom attributes
  community.general.keycloak_clientscope:
    auth_client_id: admin-cli
    auth_keycloak_url: https://auth.example.com/auth
    auth_realm: master
    auth_username: USERNAME
    auth_password: PASSWORD
    name: my-new_clientscope
    description: description-of-clientscope
    protocol: openid-connect
    protocol_mappers:
      - config:
          access.token.claim: true
          claim.name: "family_name"
          id.token.claim: true
          jsonType.label: String
          user.attribute: lastName
          userinfo.token.claim: true
        name: family name
        protocol: openid-connect
        protocolMapper: oidc-usermodel-property-mapper
      - config:
          attribute.name: Role
          attribute.nameformat: Basic
          single: false
        name: role list
        protocol: saml
        protocolMapper: saml-role-list-mapper
    attributes:
      attrib1: value1
      attrib2: value2
      attrib3:
        - with
        - numerous
        - individual
        - list
        - items
  delegate_to: localhost
a   
msg:
  description: Message as to what action was taken.
  returned: always
  type: str
  sample: "Client_scope testclientscope has been updated"

proposed:
  description: Representation of proposed client scope.
  returned: always
  type: dict
  sample: {clientId: "test"}

existing:
  description: Representation of existing client scope (sample is truncated).
  returned: always
  type: dict
  sample: {"adminUrl": "http://www.example.com/admin_url", "attributes": {"request.object.signature.alg": "RS256"}}

end_state:
  description: Representation of client scope after module execution (sample is truncated).
  returned: on success
  type: dict
  sample: {"adminUrl": "http://www.example.com/admin_url", "attributes": {"request.object.signature.alg": "RS256"}}
)KeycloakAPIcamelkeycloak_argument_spec	get_tokenKeycloakErroris_struct_included)AnsibleModulec                     | j                         } d| v rGt        | d   d       | d<   | d   D ]+  }|r|j                  dd       |j                  dd      |d<   - | S )a   Re-sorts any properties where the order so that diff's is minimised, and adds default values where appropriate so that the
    the change detection is more effective.

    :param clientscoperep: the clientscoperep dict to be sanitized
    :param remove_ids: If set to true, then the unique ID's of objects is removed to make the diff and checks for changed
                       not alert when the ID's of objects are not usually known, (e.g. for protocol_mappers)
    :return: normalised clientscoperep dict
    protocolMappersc                 f    | j                  d      | j                  d      | j                  d      fS )NnameprotocolprotocolMapper)get)xs    z/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/keycloak_clientscope.py<lambda>znormalise_cr.<locals>.<lambda>+  sT    efejejkqertutyty  {E  uF  HI  HM  HM  N^  H_  e`     )keyidNconsentRequiredF)copysortedpopr   )clientscoperep
remove_idsmappers      r   normalise_crr!     s     $((*NN*,2>BS3T  [`  -a()$%67 	MF

4& )/

3De(LF$%	M r   c                 p    | j                         }d|v rd|d<   d|v rd|d   v rd|d   d<   t        |      S )z Removes probably sensitive details from a clientscoperep representation.

    :param clientscoperep: the clientscoperep dict to be sanitized
    :return: sanitized clientrep dict
    secretno_log
attributeszsaml.signing.private.key)r   r!   )r   results     r   sanitize_crr'   6  sT       "F6#xv%)==?GF< !;<r   c                  z   t               } t        t        d      t        d      t        dg d      t        d      t        d            }t        t        dddg	      t        d
      t        d      t        d      t        d      t        dg d      t        d      t        dd|dg            }| j                  |       t        | dddgg dgg dgddi      }t        ddi i i i       }	 t	        |j
                        }t        |      }|j
                  j                  d      }|j
                  j                  d      }	|j
                  j                  d      }
|j
                  j                  d      }|j
                  j                  d      }|j
                  D cg c]G  }|t        t               j                               ddgz   vr|j
                  j                  |      |I }}|
|j                  ||       }n|j                  |
|       }|i }i }|D ]h  }|j
                  j                  |      }|dk(  r8|D cg c])  }|j                         D ci c]  \  }}|	|| c}}+ }}}}||t!        |      <   j |j#                         }|j                  |       |s|	dk(  r=|j$                  rt        dd!      |d"<   d|d#<   i |d$<   d%|d&<    |j&                  d1i | d|d#<   ||j                  d'       |j$                  rt        dt)        |      !      |d"<   |j*                  r |j&                  d1i | |j-                  ||        |j                  ||      }t)        |      |d$<   d(j/                  |d   |d   )      |d&<   n9|	dk(  rt1        |d*      t1        |d*      k(  r=d|d#<   t)        |      |d$<   d+j/                  |d   ,      |d&<    |j&                  d1i | d|d#<   |j$                  r"t        t)        |      t)        |      !      |d"<   |j*                  rjt1        |d*      }t1        |d*      }|j$                  r"t        t)        |      t)        |      !      |d"<   t3        ||       |d#<    |j&                  d1i | |j5                  ||        |Z|D ]U  }|j7                  |d   |d   |       }| |d   |d<   |j9                  |d   ||        ?|j;                  |d   ||        W |j                  |d   |       }||d$<   d-j/                  |d   .      |d&<    |j&                  d1i | n}d|d#<   |j$                  rt        t)        |      d!      |d"<   |j*                  r |j&                  d1i | |d   }
|j=                  |
|/       i |d$<   d0j/                  |d   ,      |d&<    |j&                  d1i | y# t        $ r&}|j                  t        |             Y d}~d}~ww xY wc c}w c c}}w c c}}}w )2z(
    Module execution

    :return:
    str)type)zopenid-connectsamlwsfedz	docker-v2)r*   choicesdict)r   r   r   r   configpresentabsent)defaultr-   master)r2   listr   )r*   elementsoptionsaliases)staterealmr   r   descriptionr   r%   protocol_mappersTr   r   )token
auth_realmauth_usernameauth_password)r=   r>   r?   refresh_tokenr=   )argument_specsupports_check_moderequired_one_ofrequired_togetherrequired_byF )changedmsgdiffproposedexisting	end_state)rH   Nr9   r8   r;   )r9   )beforeafterrI   rG   rL   z*Clientscope does not exist; doing nothing.rH   z6name must be specified when creating a new clientscopez0Clientscope {name} has been created with ID {id})r   r   )r   z*No changes required to clientscope {name}.)r   z!Clientscope {id} has been updated)r   )cidr9   z#Clientscope {name} has been deleted )r   r.   updater   r	   paramsr
   	fail_jsonr)   r   r   r4   keysget_clientscope_by_name get_clientscope_by_clientscopeiditemsr   r   _diff	exit_jsonr'   
check_modecreate_clientscopeformatr!   r   update_clientscope&get_clientscope_protocolmapper_by_name"update_clientscope_protocolmappers!create_clientscope_protocolmapperdelete_clientscope)rA   protmapper_spec	meta_argsmoduler&   connection_headerekcr9   r8   rO   r   r;   r   clientscope_paramsbefore_clientscope	changesetclientscope_paramnew_param_valuekvdesired_clientscopeafter_clientscopebefore_normdesired_normprotocol_mappercurrent_protocolmappers                              r   mainru   E  s    +,MUu5*Z[' O 9y(.CD8$Uue$5*Z[V$6FO^o]pq	I #/3.2F^-f-h/_.`(7'FF %Rb2VXYF%%fmm4 
V.	/BMMg&EMMg&E
--

D
!C==V$D}}(();< &,]] <d+A+C+H+H+J&KwX_N`&`` --++A.:  < <
 {77E7J@@E@R! I/ > --++,=>  22VeffQRLAam1LfOf.=	%)*+> -113y) H||!%Rr!:v %F9"$F;HF5MF&v& !y<!YZ<<!;?R3STF6NF&v& 	1?66tUC)*;<{JQQWhioWpUfgkUl R nu I /DA\RdquEvv$)y!&12E&F{# L S SYklrYs S tu   *6* !%F9||!%[9K-LT_`sTt!uv  *+=$O+,?DQ<<%)[1I0;L0I&KF6N(:<(U$Uy!   *6* !!"5U!C  +'7 vO-/-V-VWjkoWp  sB  CI  sJ  RW-V  .X*-90Ft0L-==>QRV>WYhpu=v <<=PQU=VXgot<uv !# C CDWX\D]ej C k"3F;?FFJ[\`JaFbF5MF&v& !%F9||!%[9K-LTV!Wv     *6* %T*C!!c!7"$F;AHHN`agNhHiF5MFv]  %SV$$%<,  Mfs=   ;W9 1AX+X6
1
X0<X0X6
9	X(X##X(0X6
__main__N)F)
__future__r   r   r   r*   __metaclass__DOCUMENTATIONEXAMPLESRETURNUansible_collections.community.general.plugins.module_utils.identity.keycloak.keycloakr   r   r   r	   r
   r   ansible.module_utils.basicr   r!   r'   ru   __name__rP   r   r   <module>r      s`    A @Pd`D
4I I 40 xv zF r   