blob: c20cc83e300739cd9131bd0f08e810ee3f3fe713 [file] [log] [blame]
Jakub Josef063a7532017-01-11 15:48:01 +01001import logging
2logger = logging.getLogger(__name__)
3
4set_ldap_groovy = """\
5import jenkins.model.*
6import hudson.security.*
7import org.jenkinsci.plugins.*
8
9def server = 'ldap://{server}'
10def rootDN = '{rootDN}'
11def userSearchBase = '{userSearchBase}'
12def userSearch = '{userSearch}'
13def groupSearchBase = '{groupSearchBase}'
14def managerDN = '{managerDN}'
15def managerPassword = '{managerPassword}'
16boolean inhibitInferRootDN = {inhibitInferRootDN}
17
18try{{
19ldapRealm = Class.forName("hudson.security.LDAPSecurityRealm").getConstructor(String.class, String.class, String.class, String.class, String.class, String.class, String.class, Boolean.TYPE)
20.newInstance(server, rootDN, userSearchBase, userSearch, groupSearchBase, managerDN, managerPassword, inhibitInferRootDN)
21Jenkins.instance.setSecurityRealm(ldapRealm)
22Jenkins.instance.save()
23print("SUCCESS")
24}}catch(ClassNotFoundException e){{
25 print("Cannot instantiate LDAPSecurityRealm, maybe ldap plugin not installed")
26}}
27""" # noqa
28
29set_matrix_groovy = """\
30import jenkins.model.*
31import hudson.security.*
32import com.cloudbees.plugins.credentials.*
33
34def instance = Jenkins.getInstance()
35try{{
Jakub Josef0ee470e2017-01-17 11:46:58 +010036def strategy = Class.forName("hudson.security.{matrix_class}").newInstance()
Jakub Josef063a7532017-01-11 15:48:01 +010037{strategies}
38instance.setAuthorizationStrategy(strategy)
39instance.save()
40print("SUCCESS")
41}}catch(ClassNotFoundException e){{
Jakub Josef0ee470e2017-01-17 11:46:58 +010042 print("Cannot instantiate {matrix_class}, maybe auth-matrix plugin not installed")
Jakub Josef063a7532017-01-11 15:48:01 +010043}}
Jakub Josef0ee470e2017-01-17 11:46:58 +010044""" # noqa
Jakub Josef063a7532017-01-11 15:48:01 +010045
46
Ilya Kharin3d8bffe2017-06-22 17:40:31 +040047def __virtual__():
48 '''
49 Only load if jenkins_common module exist.
50 '''
51 if 'jenkins_common.call_groovy_script' not in __salt__:
52 return (
53 False,
54 'The jenkins_security state module cannot be loaded: '
55 'jenkins_common not found')
56 return True
57
58
Jakub Josef063a7532017-01-11 15:48:01 +010059def ldap(name, server, root_dn, user_search_base, manager_dn, manager_password, user_search="", group_search_base="", inhibit_infer_root_dn=False):
60 """
61 Jenkins ldap state method
62
63 :param name: ldap state name
64 :param server: ldap server host (without ldap://)
65 :param root_dn: root domain names
66 :param user_search_base:
67 :param manager_dn:
68 :param manager_password:
69 :param user_search: optional, default empty string
70 :param group_search_base: optional, default empty string
71 :param inhibit_infer_root_dn: optional, default false
72 :returns: salt-specified state dict
73 """
74 test = __opts__['test'] # noqa
75 ret = {
76 'name': name,
77 'changes': {},
78 'result': False,
79 'comment': '',
80 }
81 result = False
82 if test:
83 status = 'CREATED'
84 ret['changes'][name] = status
85 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
86 else:
87 call_result = __salt__['jenkins_common.call_groovy_script'](
88 set_ldap_groovy, {"name": name, "server": server, "rootDN": root_dn,
Jakub Josef95ad9802017-01-17 15:59:00 +010089 "userSearchBase": user_search_base if user_search_base else "",
90 "managerDN": manager_dn if manager_dn else "",
91 "managerPassword": manager_password if manager_password else "",
92 "userSearch": user_search if user_search else "",
93 "groupSearchBase": group_search_base if group_search_base else "",
94 "inhibitInferRootDN": "true" if inhibit_infer_root_dn else "false"})
Jakub Josef063a7532017-01-11 15:48:01 +010095 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
96 status = call_result["msg"]
97 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +010098 ret['comment'] = 'Jenkins LDAP setting %s %s' % (
99 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +0100100 result = True
101 else:
102 status = 'FAILED'
103 logger.error(
104 "Jenkins security API call failure: %s", call_result["msg"])
105 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +0100106 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +0100107 ret['result'] = None if test else result
108 return ret
109
Jakub Josef0ee470e2017-01-17 11:46:58 +0100110
111def matrix(name, strategies, project_based=False):
Jakub Josef063a7532017-01-11 15:48:01 +0100112 """
113 Jenkins matrix security state method
114
115 :param name: ldap state name
Jakub Josef0ee470e2017-01-17 11:46:58 +0100116 :param strategies: dict with matrix strategies
117 :param procect_based: flag if we configuring
118 GlobalMatrix security or ProjectMatrix security
Jakub Josef063a7532017-01-11 15:48:01 +0100119 :returns: salt-specified state dict
120 """
121 test = __opts__['test'] # noqa
122 ret = {
123 'name': name,
124 'changes': {},
125 'result': False,
126 'comment': '',
127 }
128 result = False
129 if test:
130 status = 'CREATED'
131 ret['changes'][name] = status
132 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
133 else:
134 call_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josef0ee470e2017-01-17 11:46:58 +0100135 set_matrix_groovy, {"strategies": _build_strategies(strategies),
136 "matrix_class": "ProjectMatrixAuthorizationStrategy" if project_based else "GlobalMatrixAuthorizationStrategy"})
Jakub Josef063a7532017-01-11 15:48:01 +0100137 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
138 status = call_result["msg"]
139 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +0100140 ret['comment'] = 'Jenkins Matrix security setting %s %s' % (
141 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +0100142 result = True
143 else:
144 status = 'FAILED'
145 logger.error(
146 "Jenkins security API call failure: %s", call_result["msg"])
147 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +0100148 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +0100149 ret['result'] = None if test else result
150 return ret
151
152
153def _build_strategies(permissions):
154 strategies_str = ""
155 for strategy in _to_strategies_list("strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
156 strategies_str += "{}\n".format(strategy)
157 return strategies_str
158
159
160def _to_strategies_list(strategy_format, strategy_dict):
161 res = []
162 for key, value in strategy_dict.items():
163 if isinstance(value, list):
164 for user in value:
165 res.append(strategy_format.format(key, user))
166 else:
167 res.append(strategy_format.format(key, value))
168 return res
169
170
171def _to_one_dict(input_dict, input_key):
172 res = {}
173 for key, value in input_dict.items():
174 new_key = key if input_key == "" else "{}.{}".format(input_key, key)
175 if isinstance(value, dict):
176 res.update(_to_one_dict(value, new_key))
177 else:
178 res[new_key] = value
179 return res