1
0
Fork 0
mirror of https://github.com/ansible-collections/community.general.git synced 2026-05-03 08:52:55 +00:00

Reformat everything.

This commit is contained in:
Felix Fontein 2025-11-01 12:08:41 +01:00
parent 3f2213791a
commit 340ff8586d
1008 changed files with 61301 additions and 58309 deletions

View file

@ -181,46 +181,63 @@ class OTPTokenIPAClient(IPAClient):
super().__init__(module, host, port, protocol)
def otptoken_find(self, name):
return self._post_json(method='otptoken_find', name=None, item={'all': True,
'ipatokenuniqueid': name,
'timelimit': '0',
'sizelimit': '0'})
return self._post_json(
method="otptoken_find",
name=None,
item={"all": True, "ipatokenuniqueid": name, "timelimit": "0", "sizelimit": "0"},
)
def otptoken_add(self, name, item):
return self._post_json(method='otptoken_add', name=name, item=item)
return self._post_json(method="otptoken_add", name=name, item=item)
def otptoken_mod(self, name, item):
return self._post_json(method='otptoken_mod', name=name, item=item)
return self._post_json(method="otptoken_mod", name=name, item=item)
def otptoken_del(self, name):
return self._post_json(method='otptoken_del', name=name)
return self._post_json(method="otptoken_del", name=name)
def base64_to_base32(base64_string):
"""Converts base64 string to base32 string"""
b32_string = base64.b32encode(base64.b64decode(base64_string)).decode('ascii')
b32_string = base64.b32encode(base64.b64decode(base64_string)).decode("ascii")
return b32_string
def base32_to_base64(base32_string):
"""Converts base32 string to base64 string"""
b64_string = base64.b64encode(base64.b32decode(base32_string)).decode('ascii')
b64_string = base64.b64encode(base64.b32decode(base32_string)).decode("ascii")
return b64_string
def get_otptoken_dict(ansible_to_ipa, uniqueid=None, newuniqueid=None, otptype=None, secretkey=None, description=None, owner=None,
enabled=None, notbefore=None, notafter=None, vendor=None,
model=None, serial=None, algorithm=None, digits=None, offset=None,
interval=None, counter=None):
def get_otptoken_dict(
ansible_to_ipa,
uniqueid=None,
newuniqueid=None,
otptype=None,
secretkey=None,
description=None,
owner=None,
enabled=None,
notbefore=None,
notafter=None,
vendor=None,
model=None,
serial=None,
algorithm=None,
digits=None,
offset=None,
interval=None,
counter=None,
):
"""Create the dictionary of settings passed in"""
otptoken = {}
if uniqueid is not None:
otptoken[ansible_to_ipa['uniqueid']] = uniqueid
otptoken[ansible_to_ipa["uniqueid"]] = uniqueid
if newuniqueid is not None:
otptoken[ansible_to_ipa['newuniqueid']] = newuniqueid
otptoken[ansible_to_ipa["newuniqueid"]] = newuniqueid
if otptype is not None:
otptoken[ansible_to_ipa['otptype']] = otptype.upper()
otptoken[ansible_to_ipa["otptype"]] = otptype.upper()
if secretkey is not None:
# For some unknown reason, while IPA returns the secret in base64,
# it wants the secret passed in as base32. This makes it more difficult
@ -229,42 +246,42 @@ def get_otptoken_dict(ansible_to_ipa, uniqueid=None, newuniqueid=None, otptype=N
# in a different way than if it was passed in as a parameter. For
# these reasons, have the module standardize on base64 input (as parameter)
# and output (from IPA).
otptoken[ansible_to_ipa['secretkey']] = base64_to_base32(secretkey)
otptoken[ansible_to_ipa["secretkey"]] = base64_to_base32(secretkey)
if description is not None:
otptoken[ansible_to_ipa['description']] = description
otptoken[ansible_to_ipa["description"]] = description
if owner is not None:
otptoken[ansible_to_ipa['owner']] = owner
otptoken[ansible_to_ipa["owner"]] = owner
if enabled is not None:
otptoken[ansible_to_ipa['enabled']] = False if enabled else True
otptoken[ansible_to_ipa["enabled"]] = False if enabled else True
if notbefore is not None:
otptoken[ansible_to_ipa['notbefore']] = f"{notbefore}Z"
otptoken[ansible_to_ipa["notbefore"]] = f"{notbefore}Z"
if notafter is not None:
otptoken[ansible_to_ipa['notafter']] = f"{notafter}Z"
otptoken[ansible_to_ipa["notafter"]] = f"{notafter}Z"
if vendor is not None:
otptoken[ansible_to_ipa['vendor']] = vendor
otptoken[ansible_to_ipa["vendor"]] = vendor
if model is not None:
otptoken[ansible_to_ipa['model']] = model
otptoken[ansible_to_ipa["model"]] = model
if serial is not None:
otptoken[ansible_to_ipa['serial']] = serial
otptoken[ansible_to_ipa["serial"]] = serial
if algorithm is not None:
otptoken[ansible_to_ipa['algorithm']] = algorithm
otptoken[ansible_to_ipa["algorithm"]] = algorithm
if digits is not None:
otptoken[ansible_to_ipa['digits']] = str(digits)
otptoken[ansible_to_ipa["digits"]] = str(digits)
if offset is not None:
otptoken[ansible_to_ipa['offset']] = str(offset)
otptoken[ansible_to_ipa["offset"]] = str(offset)
if interval is not None:
otptoken[ansible_to_ipa['interval']] = str(interval)
otptoken[ansible_to_ipa["interval"]] = str(interval)
if counter is not None:
otptoken[ansible_to_ipa['counter']] = str(counter)
otptoken[ansible_to_ipa["counter"]] = str(counter)
return otptoken
def transform_output(ipa_otptoken, ansible_to_ipa, ipa_to_ansible):
"""Transform the output received by IPA to a format more friendly
before it is returned to the user. IPA returns even simple
strings as a list of strings. It also returns bools and
int as string. This function cleans that up before return.
before it is returned to the user. IPA returns even simple
strings as a list of strings. It also returns bools and
int as string. This function cleans that up before return.
"""
updated_otptoken = ipa_otptoken
@ -284,39 +301,38 @@ def transform_output(ipa_otptoken, ansible_to_ipa, ipa_to_ansible):
for ansible_parameter in ansible_to_ipa:
if ansible_parameter in updated_otptoken:
if isinstance(updated_otptoken[ansible_parameter], list) and len(updated_otptoken[ansible_parameter]) == 1:
if ansible_parameter in ['digits', 'offset', 'interval', 'counter']:
if ansible_parameter in ["digits", "offset", "interval", "counter"]:
updated_otptoken[ansible_parameter] = int(updated_otptoken[ansible_parameter][0])
elif ansible_parameter == 'enabled':
elif ansible_parameter == "enabled":
updated_otptoken[ansible_parameter] = bool(updated_otptoken[ansible_parameter][0])
else:
updated_otptoken[ansible_parameter] = updated_otptoken[ansible_parameter][0]
if 'secretkey' in updated_otptoken:
if isinstance(updated_otptoken['secretkey'], dict):
if '__base64__' in updated_otptoken['secretkey']:
sanitize_strings.add(updated_otptoken['secretkey']['__base64__'])
b64key = updated_otptoken['secretkey']['__base64__']
updated_otptoken.pop('secretkey')
updated_otptoken['secretkey'] = b64key
if "secretkey" in updated_otptoken:
if isinstance(updated_otptoken["secretkey"], dict):
if "__base64__" in updated_otptoken["secretkey"]:
sanitize_strings.add(updated_otptoken["secretkey"]["__base64__"])
b64key = updated_otptoken["secretkey"]["__base64__"]
updated_otptoken.pop("secretkey")
updated_otptoken["secretkey"] = b64key
sanitize_strings.add(b64key)
elif '__base32__' in updated_otptoken['secretkey']:
sanitize_strings.add(updated_otptoken['secretkey']['__base32__'])
b32key = updated_otptoken['secretkey']['__base32__']
elif "__base32__" in updated_otptoken["secretkey"]:
sanitize_strings.add(updated_otptoken["secretkey"]["__base32__"])
b32key = updated_otptoken["secretkey"]["__base32__"]
b64key = base32_to_base64(b32key)
updated_otptoken.pop('secretkey')
updated_otptoken['secretkey'] = b64key
updated_otptoken.pop("secretkey")
updated_otptoken["secretkey"] = b64key
sanitize_strings.add(b32key)
sanitize_strings.add(b64key)
return updated_otptoken, sanitize_strings
def validate_modifications(ansible_to_ipa, module, ipa_otptoken,
module_otptoken, unmodifiable_after_creation):
def validate_modifications(ansible_to_ipa, module, ipa_otptoken, module_otptoken, unmodifiable_after_creation):
"""Checks to see if the requested modifications are valid. Some elements
cannot be modified after initial creation. However, we still want to
validate arguments that are specified, but are not different than what
is currently set on the server.
cannot be modified after initial creation. However, we still want to
validate arguments that are specified, but are not different than what
is currently set on the server.
"""
modifications_valid = True
@ -329,12 +345,14 @@ def validate_modifications(ansible_to_ipa, module, ipa_otptoken,
# values in a list, even though passing them in a list (even of
# length 1) will be rejected. The module values for all elements
# other than type (totp or hotp) have this happen.
if parameter == 'otptype':
if parameter == "otptype":
ipa_value = ipa_otptoken[ansible_to_ipa[parameter]]
else:
if len(ipa_otptoken[ansible_to_ipa[parameter]]) != 1:
module.fail_json(msg="Invariant fail: Return value from IPA is not a list of length 1. Please open a bug report for the module.")
if parameter == 'secretkey':
module.fail_json(
msg="Invariant fail: Return value from IPA is not a list of length 1. Please open a bug report for the module."
)
if parameter == "secretkey":
# We stored the secret key in base32 since we had assumed that would need to
# be the format if we were contacting IPA to create it. However, we are
# now comparing it against what is already set in the IPA server, so convert
@ -343,11 +361,11 @@ def validate_modifications(ansible_to_ipa, module, ipa_otptoken,
# For the secret key, it is even more specific in that the key is returned
# in a dict, in the list, as the __base64__ entry for the IPA response.
ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]['__base64__']
if '__base64__' in ipa_otptoken[ansible_to_ipa[parameter]][0]:
ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]['__base64__']
elif '__base32__' in ipa_otptoken[ansible_to_ipa[parameter]][0]:
b32key = ipa_otptoken[ansible_to_ipa[parameter]][0]['__base32__']
ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]["__base64__"]
if "__base64__" in ipa_otptoken[ansible_to_ipa[parameter]][0]:
ipa_value = ipa_otptoken[ansible_to_ipa[parameter]][0]["__base64__"]
elif "__base32__" in ipa_otptoken[ansible_to_ipa[parameter]][0]:
b32key = ipa_otptoken[ansible_to_ipa[parameter]][0]["__base32__"]
b64key = base32_to_base64(b32key)
ipa_value = b64key
else:
@ -357,9 +375,11 @@ def validate_modifications(ansible_to_ipa, module, ipa_otptoken,
if mod_value != ipa_value:
modifications_valid = False
fail_message = (f"Parameter '{parameter}' cannot be changed once " +
f"the OTP is created and the requested value specified here ({mod_value}) " +
f"differs from what is set in the IPA server ({ipa_value})")
fail_message = (
f"Parameter '{parameter}' cannot be changed once "
+ f"the OTP is created and the requested value specified here ({mod_value}) "
+ f"differs from what is set in the IPA server ({ipa_value})"
)
module.fail_json(msg=fail_message)
return modifications_valid
@ -368,84 +388,92 @@ def validate_modifications(ansible_to_ipa, module, ipa_otptoken,
def ensure(module, client):
# dict to map from ansible parameter names to attribute names
# used by IPA (which are not so friendly).
ansible_to_ipa = {'uniqueid': 'ipatokenuniqueid',
'newuniqueid': 'rename',
'otptype': 'type',
'secretkey': 'ipatokenotpkey',
'description': 'description',
'owner': 'ipatokenowner',
'enabled': 'ipatokendisabled',
'notbefore': 'ipatokennotbefore',
'notafter': 'ipatokennotafter',
'vendor': 'ipatokenvendor',
'model': 'ipatokenmodel',
'serial': 'ipatokenserial',
'algorithm': 'ipatokenotpalgorithm',
'digits': 'ipatokenotpdigits',
'offset': 'ipatokentotpclockoffset',
'interval': 'ipatokentotptimestep',
'counter': 'ipatokenhotpcounter'}
ansible_to_ipa = {
"uniqueid": "ipatokenuniqueid",
"newuniqueid": "rename",
"otptype": "type",
"secretkey": "ipatokenotpkey",
"description": "description",
"owner": "ipatokenowner",
"enabled": "ipatokendisabled",
"notbefore": "ipatokennotbefore",
"notafter": "ipatokennotafter",
"vendor": "ipatokenvendor",
"model": "ipatokenmodel",
"serial": "ipatokenserial",
"algorithm": "ipatokenotpalgorithm",
"digits": "ipatokenotpdigits",
"offset": "ipatokentotpclockoffset",
"interval": "ipatokentotptimestep",
"counter": "ipatokenhotpcounter",
}
# Create inverse dictionary for mapping return values
ipa_to_ansible = {v: k for k, v in ansible_to_ipa.items()}
unmodifiable_after_creation = ['otptype', 'secretkey', 'algorithm',
'digits', 'offset', 'interval', 'counter']
state = module.params['state']
uniqueid = module.params['uniqueid']
unmodifiable_after_creation = ["otptype", "secretkey", "algorithm", "digits", "offset", "interval", "counter"]
state = module.params["state"]
uniqueid = module.params["uniqueid"]
module_otptoken = get_otptoken_dict(ansible_to_ipa=ansible_to_ipa,
uniqueid=module.params.get('uniqueid'),
newuniqueid=module.params.get('newuniqueid'),
otptype=module.params.get('otptype'),
secretkey=module.params.get('secretkey'),
description=module.params.get('description'),
owner=module.params.get('owner'),
enabled=module.params.get('enabled'),
notbefore=module.params.get('notbefore'),
notafter=module.params.get('notafter'),
vendor=module.params.get('vendor'),
model=module.params.get('model'),
serial=module.params.get('serial'),
algorithm=module.params.get('algorithm'),
digits=module.params.get('digits'),
offset=module.params.get('offset'),
interval=module.params.get('interval'),
counter=module.params.get('counter'))
module_otptoken = get_otptoken_dict(
ansible_to_ipa=ansible_to_ipa,
uniqueid=module.params.get("uniqueid"),
newuniqueid=module.params.get("newuniqueid"),
otptype=module.params.get("otptype"),
secretkey=module.params.get("secretkey"),
description=module.params.get("description"),
owner=module.params.get("owner"),
enabled=module.params.get("enabled"),
notbefore=module.params.get("notbefore"),
notafter=module.params.get("notafter"),
vendor=module.params.get("vendor"),
model=module.params.get("model"),
serial=module.params.get("serial"),
algorithm=module.params.get("algorithm"),
digits=module.params.get("digits"),
offset=module.params.get("offset"),
interval=module.params.get("interval"),
counter=module.params.get("counter"),
)
ipa_otptoken = client.otptoken_find(name=uniqueid)
if ansible_to_ipa['newuniqueid'] in module_otptoken:
if ansible_to_ipa["newuniqueid"] in module_otptoken:
# Check to see if the new unique id is already taken in use
ipa_otptoken_new = client.otptoken_find(name=module_otptoken[ansible_to_ipa['newuniqueid']])
ipa_otptoken_new = client.otptoken_find(name=module_otptoken[ansible_to_ipa["newuniqueid"]])
if ipa_otptoken_new:
module.fail_json(msg=(f"Requested rename through newuniqueid to {module_otptoken[ansible_to_ipa['newuniqueid']]} "
"failed because the new unique id is already in use"))
module.fail_json(
msg=(
f"Requested rename through newuniqueid to {module_otptoken[ansible_to_ipa['newuniqueid']]} "
"failed because the new unique id is already in use"
)
)
changed = False
if state == 'present':
if state == "present":
if not ipa_otptoken:
changed = True
if not module.check_mode:
# It would not make sense to have a rename after creation, so if the user
# specified a newuniqueid, just replace the uniqueid with the updated one
# before creation
if ansible_to_ipa['newuniqueid'] in module_otptoken:
module_otptoken[ansible_to_ipa['uniqueid']] = module_otptoken[ansible_to_ipa['newuniqueid']]
uniqueid = module_otptoken[ansible_to_ipa['newuniqueid']]
module_otptoken.pop(ansible_to_ipa['newuniqueid'])
if ansible_to_ipa["newuniqueid"] in module_otptoken:
module_otptoken[ansible_to_ipa["uniqueid"]] = module_otptoken[ansible_to_ipa["newuniqueid"]]
uniqueid = module_otptoken[ansible_to_ipa["newuniqueid"]]
module_otptoken.pop(ansible_to_ipa["newuniqueid"])
# IPA wants the unique id in the first position and not as a key/value pair.
# Get rid of it from the otptoken dict and just specify it in the name field
# for otptoken_add.
if ansible_to_ipa['uniqueid'] in module_otptoken:
module_otptoken.pop(ansible_to_ipa['uniqueid'])
if ansible_to_ipa["uniqueid"] in module_otptoken:
module_otptoken.pop(ansible_to_ipa["uniqueid"])
module_otptoken['all'] = True
module_otptoken["all"] = True
ipa_otptoken = client.otptoken_add(name=uniqueid, item=module_otptoken)
else:
if not validate_modifications(ansible_to_ipa, module, ipa_otptoken,
module_otptoken, unmodifiable_after_creation):
if not validate_modifications(
ansible_to_ipa, module, ipa_otptoken, module_otptoken, unmodifiable_after_creation
):
module.fail_json(msg="Modifications requested in module are not valid")
# IPA will reject 'modifications' that do not actually modify anything
@ -460,14 +488,13 @@ def ensure(module, client):
if len(diff) > 0:
changed = True
if not module.check_mode:
# IPA wants the unique id in the first position and not as a key/value pair.
# Get rid of it from the otptoken dict and just specify it in the name field
# for otptoken_mod.
if ansible_to_ipa['uniqueid'] in module_otptoken:
module_otptoken.pop(ansible_to_ipa['uniqueid'])
if ansible_to_ipa["uniqueid"] in module_otptoken:
module_otptoken.pop(ansible_to_ipa["uniqueid"])
module_otptoken['all'] = True
module_otptoken["all"] = True
ipa_otptoken = client.otptoken_mod(name=uniqueid, item=module_otptoken)
else:
if ipa_otptoken:
@ -485,36 +512,38 @@ def ensure(module, client):
def main():
argument_spec = ipa_argument_spec()
argument_spec.update(uniqueid=dict(type='str', aliases=['name'], required=True),
newuniqueid=dict(type='str'),
otptype=dict(type='str', choices=['totp', 'hotp']),
secretkey=dict(type='str', no_log=True),
description=dict(type='str'),
owner=dict(type='str'),
enabled=dict(type='bool', default=True),
notbefore=dict(type='str'),
notafter=dict(type='str'),
vendor=dict(type='str'),
model=dict(type='str'),
serial=dict(type='str'),
state=dict(type='str', choices=['present', 'absent'], default='present'),
algorithm=dict(type='str', choices=['sha1', 'sha256', 'sha384', 'sha512']),
digits=dict(type='int', choices=[6, 8]),
offset=dict(type='int'),
interval=dict(type='int'),
counter=dict(type='int'))
argument_spec.update(
uniqueid=dict(type="str", aliases=["name"], required=True),
newuniqueid=dict(type="str"),
otptype=dict(type="str", choices=["totp", "hotp"]),
secretkey=dict(type="str", no_log=True),
description=dict(type="str"),
owner=dict(type="str"),
enabled=dict(type="bool", default=True),
notbefore=dict(type="str"),
notafter=dict(type="str"),
vendor=dict(type="str"),
model=dict(type="str"),
serial=dict(type="str"),
state=dict(type="str", choices=["present", "absent"], default="present"),
algorithm=dict(type="str", choices=["sha1", "sha256", "sha384", "sha512"]),
digits=dict(type="int", choices=[6, 8]),
offset=dict(type="int"),
interval=dict(type="int"),
counter=dict(type="int"),
)
module = AnsibleModule(argument_spec=argument_spec,
supports_check_mode=True)
module = AnsibleModule(argument_spec=argument_spec, supports_check_mode=True)
client = OTPTokenIPAClient(module=module,
host=module.params['ipa_host'],
port=module.params['ipa_port'],
protocol=module.params['ipa_prot'])
client = OTPTokenIPAClient(
module=module,
host=module.params["ipa_host"],
port=module.params["ipa_port"],
protocol=module.params["ipa_prot"],
)
try:
client.login(username=module.params['ipa_user'],
password=module.params['ipa_pass'])
client.login(username=module.params["ipa_user"], password=module.params["ipa_pass"])
changed, otptoken = ensure(module, client)
except Exception as e:
module.fail_json(msg=to_native(e), exception=traceback.format_exc())
@ -522,5 +551,5 @@ def main():
module.exit_json(changed=changed, otptoken=otptoken)
if __name__ == '__main__':
if __name__ == "__main__":
main()