
    Vh                          d dl mZmZmZ eZdZdZdZd dl	Z	d dl
Z
d dlZd dlmZ d dlmZ d dlmZ d	Z G d
 de      Z G d de      Zd Zd Zd Zd Zd Zd Zedk(  r e        yy)    )absolute_importdivisionprint_functiona&  
module: github_key
short_description: Manage GitHub access keys
description:
  - Creates, removes, or updates GitHub access keys.
extends_documentation_fragment:
  - community.general.attributes
attributes:
  check_mode:
    support: full
  diff_mode:
    support: none
options:
  token:
    description:
      - GitHub Access Token with permission to list and create public keys.
    required: true
    type: str
  name:
    description:
      - SSH key name.
    required: true
    type: str
  pubkey:
    description:
      - SSH public key value. Required when O(state=present).
    type: str
  state:
    description:
      - Whether to remove a key, ensure that it exists, or update its value.
    choices: ['present', 'absent']
    default: 'present'
    type: str
  force:
    description:
      - The default is V(true), which will replace the existing remote key if it is different than O(pubkey). If V(false),
        the key will only be set if no key with the given O(name) exists.
    type: bool
    default: true

author: Robert Estelle (@erydo)
a  
deleted_keys:
  description: An array of key objects that were deleted. Only present on state=absent.
  type: list
  returned: When state=absent
  sample:
    [
      {
        "id": 0,
        "key": "BASE64 encoded key",
        "url": "http://example.com/github key",
        "created_at": "YYYY-MM-DDTHH:MM:SZ",
        "read_only": false
      }
    ]
matching_keys:
  description: An array of keys matching the specified name. Only present on state=present.
  type: list
  returned: When state=present
  sample:
    [
      {
        "id": 0,
        "key": "BASE64 encoded key",
        "url": "http://example.com/github key",
        "created_at": "YYYY-MM-DDTHH:MM:SZ",
        "read_only": false
      }
    ]
key:
  description: Metadata about the key just created. Only present on state=present.
  type: dict
  returned: success
  sample:
    {
      "id": 0,
      "key": "BASE64 encoded key",
      "url": "http://example.com/github key",
      "created_at": "YYYY-MM-DDTHH:MM:SZ",
      "read_only": false
    }
an  
- name: Read SSH public key to authorize
  ansible.builtin.shell: cat /home/foo/.ssh/id_rsa.pub
  register: ssh_pub_key

- name: Authorize key with GitHub
  local_action:
    module: github_key
    name: Access Key for Some Machine
    token: '{{ github_access_token }}'
    pubkey: '{{ ssh_pub_key.stdout }}'

# Alternatively, a single task can be used reading a key from a file on the controller
- name: Authorize key with GitHub
  community.general.github_key:
    name: Access Key for Some Machine
    token: '{{ github_access_token }}'
    pubkey: "{{ lookup('ansible.builtin.file', '/home/foo/.ssh/id_rsa.pub') }}"
N)AnsibleModule)	fetch_url)nowzhttps://api.github.comc                       e Zd Zd Zd Zd Zy)GitHubResponsec                 <    |j                         | _        || _        y N)readcontentinfo)selfresponser   s      p/home/dcms/DCMS/lib/python3.12/site-packages/ansible_collections/community/general/plugins/modules/github_key.py__init__zGitHubResponse.__init__   s    }}	    c                 @    t        j                  | j                        S r   )jsonloadsr   )r   s    r   r   zGitHubResponse.json   s    zz$,,''r   c                     i }d| j                   v r4| j                   d   }t        j                  d|      }|D ]
  \  }}|||<    |S )Nlinkz<([^>]+)>; rel="([^"]+)")r   refindall)r   linkslink_headermatchesurlrels         r   r   zGitHubResponse.links   sS    TYY))F+Kjj!;[IG# !S c
!r   N)__name__
__module____qualname__r   r   r    r   r   r
   r
      s    (r   r
   c                       e Zd Zd ZddZy)GitHubSessionc                      || _         || _        y r   )moduletoken)r   r(   r)   s      r   r   zGitHubSession.__init__   s    
r   Nc           	          d| j                   z  ddd}t        | j                  ||||      \  }}d|d   cxk  rdk  s*n | j                  j                  d	|d
|d|d          t	        ||      S )Nztoken %szapplication/jsonzapplication/vnd.github.v3+json)AuthorizationzContent-TypeAccept)methoddataheaders   statusi  z failed to send request z to z: msgr2   )r)   r   r(   	fail_jsonr
   )r   r-   r   r.   r/   r   r   s          r   requestzGitHubSession.request   s    '$**4.6

 #KKV$I$tH~++KK!!T%[2 " 4 h--r   r   )r!   r"   r#   r   r5   r$   r   r   r&   r&      s    .r   r&   c                     t         dz   }g }|rS| j                  d|      }|j                  |j                                |j	                         j                  d      }|rS|S )N
/user/keysGETnext)API_BASEr5   extendr   r   get)sessionr   resultrs       r   get_all_keysr@      sV    
\
!CF
OOE3'affhggimmF#  Mr   c           	          |r2t               }d||dt        j                  j                  |d      dddS | j                  dt        dz   t        j                  ||d      	      j                         S )
Nr   z(http://example.com/CHECK_MODE_GITHUB_KEYz%Y-%m-%dT%H:%M:%SZF)idkeytitler   
created_at	read_onlyverifiedPOSTr7   )rD   rC   )r.   )r   datetimestrftimer5   r:   r   dumps)r=   namepubkey
check_modenow_ts        r   
create_keyrP      s~    ="++44U<PQ
 	
 |#d6:;  = >BTV	Dr   c                 V    |ry |D ]!  }| j                  dt        d|d   z  z          # y )NDELETEz/user/keys/%srB   )r5   r:   )r=   	to_deleterN   rC   s       r   delete_keysrT      s5     J(_s4y-H"HIJr   c                     t        |       D cg c]  }|d   |k(  s| }}t        | ||       t        |      |dS c c}w )NrD   rN   )changeddeleted_keys)r@   rT   bool)r=   rL   rN   rC   rS   s        r   ensure_key_absentrZ      sK     ,W 5NW9MNINz:I%' ' Os   >>c                    t        |      }|D cg c]  }|d   |k(  s| }}g }	|j                  d      d   }
|D ]L  }|d   j                  d      d   }|
|k(  s |d   |k7  s)| j                  dj                  |d                N |r1|r/|d   d   j                  d      d   |
k7  rt	        |||       |g }}	|st        ||||      }n|d   }t        |	xs |       |	||d	S c c}w )
NrD       rC   zLanother key with the same content is already registered under the name |{0}|r3   r   rV   )rW   rX   matching_keysrC   )r@   splitr4   formatrT   rP   rY   )r(   r=   rL   rM   forcerN   all_keyskr^   rX   new_signaturerC   existing_signatures                r   ensure_key_presentrf      s*   G$H (?1AgJ$,>Q?M?LLL%a(M > Z--c215..3w<43G'(.s7|(<  >> =#3E#:#@#@#Ea#HM#YG]zB)6}$:FA 9M(9:$&	 ) @s
   C*C*c                  D   dddddii ddgdddddd	} t        | d
      }|j                  d   }|j                  d   }|j                  d   }|j                  d   }|j                  j                  d      }|r2|j                  d      }t	        |      dk  r*|j                  d       n|dk(  r|j                  d       t        ||      }|dk(  rt        ||||||j                        }	n|dk(  rt        |||j                        }	 |j                  di 	 y )NT)requiredno_logrh   presentabsent)choicesdefaultrY   )rm   type)r)   rL   rM   statera   )argument_specsupports_check_moder)   rL   ro   ra   rM   r\      z("pubkey" parameter has an invalid formatr3   z'"pubkey" is required when state=present)ra   rN   rV   r$   )r   paramsr<   r_   lenr4   r&   rf   rN   rZ   	exit_json)
rp   r(   r)   rL   ro   ra   rM   pubkey_partsr=   r>   s
             r   mainrw      s<   "d3T"'2yI!62M # F
 MM'"E== DMM'"EMM'"E]]x(F||C(|q !KL	)	FGFE*G	#FGT6/5/@/@B	(	"7DV=N=NOFvr   __main__)
__future__r   r   r   rn   __metaclass__DOCUMENTATIONRETURNEXAMPLESrI   r   r   ansible.module_utils.basicr   ansible.module_utils.urlsr   Cansible_collections.community.general.plugins.module_utils.datetimer   r:   objectr
   r&   r@   rP   rT   rZ   rf   rw   r!   r$   r   r   <module>r      s    A @)V)
V(   	 4 /
 $V $.F .(D&J'<"J zF r   