Debian Codegraph @

ansible_collections/fortinet/fortios/plugins/modules/fortios_user_scim.py

raw symbols SCIP
1 #!/usr/bin/python
2 from __future__ import absolute_import, division, print_function
3
4 # Copyright: (c) 2022 Fortinet
5 # GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
6 #
7 # This program is free software: you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation, either version 3 of the License, or
10 # (at your option) any later version.
11
12 __metaclass__ = type
13
14 ANSIBLE_METADATA = {
15 "status": ["preview"],
16 "supported_by": "community",
17 "metadata_version": "1.1",
18 }
19
20 DOCUMENTATION = """
21 ---
22 module: fortios_user_scim
23 short_description: Configure SCIM client entries in Fortinet's FortiOS and FortiGate.
24 description:
25 - This module is able to configure a FortiGate or FortiOS (FOS) device by allowing the
26 user to set and modify user feature and scim category.
27 Examples include all parameters and values need to be adjusted to datasources before usage.
28 Tested with FOS v6.0.0
29 version_added: "2.0.0"
30 author:
31 - Link Zheng (@chillancezen)
32 - Jie Xue (@JieX19)
33 - Hongbin Lu (@fgtdev-hblu)
34 - Frank Shen (@frankshen01)
35 - Miguel Angel Munoz (@mamunozgonzalez)
36 - Nicolas Thomas (@thomnico)
37 notes:
38 - Legacy fortiosapi has been deprecated, httpapi is the preferred way to run playbooks
39
40 - The module supports check_mode.
41
42 requirements:
43 - ansible>=2.16
44 options:
45 access_token:
46 description:
47 - Token-based authentication.
48 Generated from GUI of Fortigate.
49 type: str
50 required: false
51 enable_log:
52 description:
53 - Enable/Disable logging for task.
54 type: bool
55 required: false
56 default: false
57 vdom:
58 description:
59 - Virtual domain, among those defined previously. A vdom is a
60 virtual instance of the FortiGate that can be configured and
61 used as a different unit.
62 type: str
63 default: root
64 member_path:
65 type: str
66 description:
67 - Member attribute path to operate on.
68 - Delimited by a slash character if there are more than one attribute.
69 - Parameter marked with member_path is legitimate for doing member operation.
70 member_state:
71 type: str
72 description:
73 - Add or delete a member under specified attribute path.
74 - When member_state is specified, the state option is ignored.
75 choices:
76 - 'present'
77 - 'absent'
78
79 state:
80 description:
81 - Indicates whether to create or remove the object.
82 type: str
83 required: true
84 choices:
85 - 'present'
86 - 'absent'
87 user_scim:
88 description:
89 - Configure SCIM client entries.
90 default: null
91 type: dict
92 suboptions:
93 auth_method:
94 description:
95 - TLS client authentication methods .
96 type: str
97 choices:
98 - 'token'
99 - 'base'
100 base_url:
101 description:
102 - Server URL to receive SCIM create, read, update, delete (CRUD) requests.
103 type: str
104 cascade:
105 description:
106 - Enable/disable to follow SCIM users/groups changes in IDP.
107 type: str
108 choices:
109 - 'disable'
110 - 'enable'
111 certificate:
112 description:
113 - Certificate for client verification during TLS handshake. Source vpn.certificate.ca.name vpn.certificate.remote.name certificate.ca.name
114 certificate.remote.name.
115 type: str
116 client_authentication_method:
117 description:
118 - TLS client authentication methods .
119 type: str
120 choices:
121 - 'token'
122 - 'base'
123 client_identity_check:
124 description:
125 - Enable/disable client identity check.
126 type: str
127 choices:
128 - 'enable'
129 - 'disable'
130 client_secret_token:
131 description:
132 - Client secret token for authentication.
133 type: str
134 id:
135 description:
136 - SCIM client ID.
137 type: int
138 name:
139 description:
140 - SCIM client name.
141 required: true
142 type: str
143 secret:
144 description:
145 - Secret for token verification or base authentication.
146 type: str
147 status:
148 description:
149 - Enable/disable System for Cross-domain Identity Management (SCIM).
150 type: str
151 choices:
152 - 'enable'
153 - 'disable'
154 token_certificate:
155 description:
156 - Certificate for token verification. Source vpn.certificate.remote.name vpn.certificate.local.name.
157 type: str
158 """
159
160 EXAMPLES = """
161 - name: Configure SCIM client entries.
162 fortinet.fortios.fortios_user_scim:
163 vdom: "{{ vdom }}"
164 state: "present"
165 access_token: "<your_own_value>"
166 user_scim:
167 auth_method: "token"
168 base_url: "<your_own_value>"
169 cascade: "disable"
170 certificate: "<your_own_value> (source vpn.certificate.ca.name vpn.certificate.remote.name certificate.ca.name certificate.remote.name)"
171 client_authentication_method: "token"
172 client_identity_check: "enable"
173 client_secret_token: "<your_own_value>"
174 id: "10"
175 name: "default_name_11"
176 secret: "<your_own_value>"
177 status: "enable"
178 token_certificate: "<your_own_value> (source vpn.certificate.remote.name vpn.certificate.local.name)"
179 """
180
181 RETURN = """
182 build:
183 description: Build number of the fortigate image
184 returned: always
185 type: str
186 sample: '1547'
187 http_method:
188 description: Last method used to provision the content into FortiGate
189 returned: always
190 type: str
191 sample: 'PUT'
192 http_status:
193 description: Last result given by FortiGate on last operation applied
194 returned: always
195 type: str
196 sample: "200"
197 mkey:
198 description: Master key (id) used in the last call to FortiGate
199 returned: success
200 type: str
201 sample: "id"
202 name:
203 description: Name of the table used to fulfill the request
204 returned: always
205 type: str
206 sample: "urlfilter"
207 path:
208 description: Path of the table used to fulfill the request
209 returned: always
210 type: str
211 sample: "webfilter"
212 revision:
213 description: Internal revision number
214 returned: always
215 type: str
216 sample: "17.0.2.10658"
217 serial:
218 description: Serial number of the unit
219 returned: always
220 type: str
221 sample: "FGVMEVYYQT3AB5352"
222 status:
223 description: Indication of the operation's result
224 returned: always
225 type: str
226 sample: "success"
227 vdom:
228 description: Virtual domain used
229 returned: always
230 type: str
231 sample: "root"
232 version:
233 description: Version of the FortiGate
234 returned: always
235 type: str
236 sample: "v5.6.3"
237 """
238 from ansible.module_utils.basic import AnsibleModule
239 from ansible.module_utils.connection import Connection
240 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
241 FortiOSHandler,
242 )
243 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
244 check_legacy_fortiosapi,
245 )
246 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
247 schema_to_module_spec,
248 )
249 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.fortios import (
250 check_schema_versioning,
251 )
252 from ansible_collections.fortinet.fortios.plugins.module_utils.fortimanager.common import (
253 FAIL_SOCKET_MSG,
254 )
255 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.data_post_processor import (
256 remove_invalid_fields,
257 )
258 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
259 is_same_comparison,
260 )
261 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
262 serialize,
263 )
264 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
265 find_current_values,
266 )
267 from ansible_collections.fortinet.fortios.plugins.module_utils.fortios.comparison import (
268 unify_data_format,
269 )
270
271
272 def filter_user_scim_data(json):
273 option_list = [
274 "auth_method",
275 "base_url",
276 "cascade",
277 "certificate",
278 "client_authentication_method",
279 "client_identity_check",
280 "client_secret_token",
281 "id",
282 "name",
283 "secret",
284 "status",
285 "token_certificate",
286 ]
287
288 json = remove_invalid_fields(json)
289 dictionary = {}
290
291 for attribute in option_list:
292 if attribute in json and json[attribute] is not None:
293 dictionary[attribute] = json[attribute]
294
295 return dictionary
296
297
298 def underscore_to_hyphen(data):
299 new_data = None
300 if isinstance(data, list):
301 new_data = []
302 for i, elem in enumerate(data):
303 new_data.append(underscore_to_hyphen(elem))
304 elif isinstance(data, dict):
305 new_data = {}
306 for k, v in data.items():
307 new_data[k.replace("_", "-")] = underscore_to_hyphen(v)
308 else:
309 return data
310 return new_data
311
312
313 def user_scim(data, fos, check_mode=False):
314
315 state = None
316 vdom = data["vdom"]
317 parameters = None
318 state = data.get("state", None)
319 user_scim_data = data["user_scim"]
320
321 filtered_data = filter_user_scim_data(user_scim_data)
322 converted_data = underscore_to_hyphen(filtered_data)
323
324 # check_mode starts from here
325 if check_mode:
326 diff = {
327 "before": "",
328 "after": filtered_data,
329 }
330 mkeyname = fos.get_mkeyname(None, None)
331 mkey = fos.get_mkey("user", "scim", filtered_data, vdom=vdom)
332 current_data = fos.get(
333 "user", "scim", vdom=vdom, mkey=mkey, parameters=parameters
334 )
335 is_existed = (
336 current_data
337 and current_data.get("http_status") == 200
338 and (
339 mkeyname
340 and isinstance(current_data.get("results"), list)
341 and len(current_data["results"]) > 0
342 or not mkeyname
343 and current_data["results"] # global object response
344 )
345 )
346
347 # 2. if it exists and the state is 'present' then compare current settings with desired
348 if state == "present" or state is True or state is None:
349 # for non global modules, mkeyname must exist and it's a new module when mkey is None
350 if mkeyname is not None and mkey is None:
351 return False, True, filtered_data, diff
352
353 # if mkey exists then compare each other
354 # record exits and they're matched or not
355 copied_filtered_data = filtered_data.copy()
356 copied_filtered_data.pop(mkeyname, None)
357 unified_filtered_data = unify_data_format(copied_filtered_data)
358
359 current_data_results = current_data.get("results", {})
360 current_config = (
361 current_data_results[0]
362 if mkeyname
363 and isinstance(current_data_results, list)
364 and len(current_data_results) > 0
365 else current_data_results
366 )
367 if is_existed:
368 unified_current_values = find_current_values(
369 unified_filtered_data,
370 unify_data_format(current_config),
371 )
372
373 is_same = is_same_comparison(
374 serialize(unified_current_values), serialize(unified_filtered_data)
375 )
376
377 return (
378 False,
379 not is_same,
380 filtered_data,
381 {"before": unified_current_values, "after": unified_filtered_data},
382 )
383
384 # record does not exist
385 return False, True, filtered_data, diff
386
387 if state == "absent":
388 if mkey is None:
389 return (
390 False,
391 False,
392 filtered_data,
393 {"before": current_data["results"][0], "after": ""},
394 )
395
396 if is_existed:
397 return (
398 False,
399 True,
400 filtered_data,
401 {"before": current_data["results"][0], "after": ""},
402 )
403 return False, False, filtered_data, {}
404
405 return True, False, {"reason: ": "Must provide state parameter"}, {}
406 # pass post processed data to member operations
407 # no need to do underscore_to_hyphen since do_member_operation handles it by itself
408 data_copy = data.copy()
409 data_copy["user_scim"] = filtered_data
410 fos.do_member_operation(
411 "user",
412 "scim",
413 data_copy,
414 )
415
416 if state == "present" or state is True:
417 return fos.set(
418 "user", "scim", data=converted_data, vdom=vdom, parameters=parameters
419 )
420
421 elif state == "absent":
422 return fos.delete(
423 "user",
424 "scim",
425 mkey=converted_data["name"],
426 vdom=vdom,
427 parameters=parameters,
428 )
429 else:
430 fos._module.fail_json(msg="state must be present or absent!")
431
432
433 def is_successful_status(resp):
434 return (
435 "status" in resp
436 and resp["status"] == "success"
437 or "http_status" in resp
438 and resp["http_status"] == 200
439 or "http_method" in resp
440 and resp["http_method"] == "DELETE"
441 and resp["http_status"] == 404
442 )
443
444
445 def fortios_user(data, fos, check_mode):
446
447 if data["user_scim"]:
448 resp = user_scim(data, fos, check_mode)
449 else:
450 fos._module.fail_json(msg="missing task body: %s" % ("user_scim"))
451 if isinstance(resp, tuple) and len(resp) == 4:
452 return resp
453 return (
454 not is_successful_status(resp),
455 is_successful_status(resp)
456 and (resp["revision_changed"] if "revision_changed" in resp else True),
457 resp,
458 {},
459 )
460
461
462 versioned_schema = {
463 "type": "list",
464 "elements": "dict",
465 "children": {
466 "name": {"v_range": [["v7.6.0", ""]], "type": "string", "required": True},
467 "id": {"v_range": [["v7.6.0", ""]], "type": "integer"},
468 "status": {
469 "v_range": [["v7.6.0", ""]],
470 "type": "string",
471 "options": [{"value": "enable"}, {"value": "disable"}],
472 },
473 "base_url": {"v_range": [["v7.6.0", ""]], "type": "string"},
474 "auth_method": {
475 "v_range": [["v7.6.1", ""]],
476 "type": "string",
477 "options": [{"value": "token"}, {"value": "base"}],
478 },
479 "token_certificate": {"v_range": [["v7.6.1", ""]], "type": "string"},
480 "secret": {"v_range": [["v7.6.1", ""]], "type": "string"},
481 "certificate": {"v_range": [["v7.6.0", ""]], "type": "string"},
482 "client_identity_check": {
483 "v_range": [["v7.6.0", ""]],
484 "type": "string",
485 "options": [{"value": "enable"}, {"value": "disable"}],
486 },
487 "cascade": {
488 "v_range": [["v7.6.4", ""]],
489 "type": "string",
490 "options": [{"value": "disable"}, {"value": "enable"}],
491 },
492 "client_authentication_method": {
493 "v_range": [["v7.6.0", "v7.6.0"]],
494 "type": "string",
495 "options": [{"value": "token"}, {"value": "base"}],
496 },
497 "client_secret_token": {"v_range": [["v7.6.0", "v7.6.0"]], "type": "string"},
498 },
499 "v_range": [["v7.6.0", ""]],
500 }
501
502
503 def main():
504 module_spec = schema_to_module_spec(versioned_schema)
505 mkeyname = "name"
506 fields = {
507 "access_token": {"required": False, "type": "str", "no_log": True},
508 "enable_log": {"required": False, "type": "bool", "default": False},
509 "vdom": {"required": False, "type": "str", "default": "root"},
510 "member_path": {"required": False, "type": "str"},
511 "member_state": {
512 "type": "str",
513 "required": False,
514 "choices": ["present", "absent"],
515 },
516 "state": {"required": True, "type": "str", "choices": ["present", "absent"]},
517 "user_scim": {
518 "required": False,
519 "type": "dict",
520 "default": None,
521 "options": {},
522 },
523 }
524 for attribute_name in module_spec["options"]:
525 fields["user_scim"]["options"][attribute_name] = module_spec["options"][
526 attribute_name
527 ]
528 if mkeyname and mkeyname == attribute_name:
529 fields["user_scim"]["options"][attribute_name]["required"] = True
530
531 module = AnsibleModule(argument_spec=fields, supports_check_mode=True)
532 check_legacy_fortiosapi(module)
533
534 is_error = False
535 has_changed = False
536 result = None
537 diff = None
538
539 versions_check_result = None
540 if module._socket_path:
541 connection = Connection(module._socket_path)
542 if "access_token" in module.params:
543 connection.set_custom_option("access_token", module.params["access_token"])
544
545 if "enable_log" in module.params:
546 connection.set_custom_option("enable_log", module.params["enable_log"])
547 else:
548 connection.set_custom_option("enable_log", False)
549 fos = FortiOSHandler(connection, module, mkeyname, admin_passwd_header=False)
550 versions_check_result = check_schema_versioning(
551 fos, versioned_schema, "user_scim"
552 )
553
554 is_error, has_changed, result, diff = fortios_user(
555 module.params, fos, module.check_mode
556 )
557
558 else:
559 module.fail_json(**FAIL_SOCKET_MSG)
560
561 if versions_check_result and versions_check_result["matched"] is False:
562 module.warn(
563 "Ansible has detected version mismatch between FortOS system and your playbook, see more details by specifying option -vvv"
564 )
565
566 if not is_error:
567 if versions_check_result and versions_check_result["matched"] is False:
568 module.exit_json(
569 changed=has_changed,
570 version_check_warning=versions_check_result,
571 meta=result,
572 diff=diff,
573 )
574 else:
575 module.exit_json(changed=has_changed, meta=result, diff=diff)
576 else:
577 if versions_check_result and versions_check_result["matched"] is False:
578 module.fail_json(
579 msg="Error in repo",
580 version_check_warning=versions_check_result,
581 meta=result,
582 )
583 else:
584 module.fail_json(msg="Error in repo", meta=result)
585
586
587 if __name__ == "__main__":
588 main()