blob: 6442e2bccf793101fa008d48f316900740d26aea [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
Andrey6606be02017-08-02 17:09:42 -05009def server = '{server}'
Jakub Josef063a7532017-01-11 15:48:01 +010010def 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
Andrey6606be02017-08-02 17:09:42 -050064 :param server: ldap server host
Jakub Josef063a7532017-01-11 15:48:01 +010065 :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
Andrey6606be02017-08-02 17:09:42 -050082 if not server.startswith("ldap:") and not server.startswith("ldaps:"):
83 server = "ldap://{server}".format(server=server)
84
Jakub Josef063a7532017-01-11 15:48:01 +010085 if test:
86 status = 'CREATED'
87 ret['changes'][name] = status
88 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
89 else:
90 call_result = __salt__['jenkins_common.call_groovy_script'](
91 set_ldap_groovy, {"name": name, "server": server, "rootDN": root_dn,
Jakub Josef95ad9802017-01-17 15:59:00 +010092 "userSearchBase": user_search_base if user_search_base else "",
93 "managerDN": manager_dn if manager_dn else "",
94 "managerPassword": manager_password if manager_password else "",
95 "userSearch": user_search if user_search else "",
96 "groupSearchBase": group_search_base if group_search_base else "",
97 "inhibitInferRootDN": "true" if inhibit_infer_root_dn else "false"})
Jakub Josef063a7532017-01-11 15:48:01 +010098 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
99 status = call_result["msg"]
100 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +0100101 ret['comment'] = 'Jenkins LDAP setting %s %s' % (
102 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +0100103 result = True
104 else:
105 status = 'FAILED'
106 logger.error(
107 "Jenkins security API call failure: %s", call_result["msg"])
108 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +0100109 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +0100110 ret['result'] = None if test else result
111 return ret
112
Jakub Josef0ee470e2017-01-17 11:46:58 +0100113
114def matrix(name, strategies, project_based=False):
Jakub Josef063a7532017-01-11 15:48:01 +0100115 """
116 Jenkins matrix security state method
117
118 :param name: ldap state name
Jakub Josef0ee470e2017-01-17 11:46:58 +0100119 :param strategies: dict with matrix strategies
120 :param procect_based: flag if we configuring
121 GlobalMatrix security or ProjectMatrix security
Jakub Josef063a7532017-01-11 15:48:01 +0100122 :returns: salt-specified state dict
123 """
124 test = __opts__['test'] # noqa
125 ret = {
126 'name': name,
127 'changes': {},
128 'result': False,
129 'comment': '',
130 }
131 result = False
132 if test:
133 status = 'CREATED'
134 ret['changes'][name] = status
135 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
136 else:
137 call_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josef0ee470e2017-01-17 11:46:58 +0100138 set_matrix_groovy, {"strategies": _build_strategies(strategies),
139 "matrix_class": "ProjectMatrixAuthorizationStrategy" if project_based else "GlobalMatrixAuthorizationStrategy"})
Jakub Josef063a7532017-01-11 15:48:01 +0100140 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
141 status = call_result["msg"]
142 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +0100143 ret['comment'] = 'Jenkins Matrix security setting %s %s' % (
144 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +0100145 result = True
146 else:
147 status = 'FAILED'
148 logger.error(
149 "Jenkins security API call failure: %s", call_result["msg"])
150 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +0100151 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +0100152 ret['result'] = None if test else result
153 return ret
154
155
156def _build_strategies(permissions):
157 strategies_str = ""
158 for strategy in _to_strategies_list("strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
159 strategies_str += "{}\n".format(strategy)
160 return strategies_str
161
162
163def _to_strategies_list(strategy_format, strategy_dict):
164 res = []
165 for key, value in strategy_dict.items():
166 if isinstance(value, list):
167 for user in value:
168 res.append(strategy_format.format(key, user))
169 else:
170 res.append(strategy_format.format(key, value))
171 return res
172
173
174def _to_one_dict(input_dict, input_key):
175 res = {}
176 for key, value in input_dict.items():
177 new_key = key if input_key == "" else "{}.{}".format(input_key, key)
178 if isinstance(value, dict):
179 res.update(_to_one_dict(value, new_key))
180 else:
181 res[new_key] = value
182 return res