blob: d9d411f00e0026993812a0b58d3b5a7dd7516bc3 [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
47def ldap(name, server, root_dn, user_search_base, manager_dn, manager_password, user_search="", group_search_base="", inhibit_infer_root_dn=False):
48 """
49 Jenkins ldap state method
50
51 :param name: ldap state name
52 :param server: ldap server host (without ldap://)
53 :param root_dn: root domain names
54 :param user_search_base:
55 :param manager_dn:
56 :param manager_password:
57 :param user_search: optional, default empty string
58 :param group_search_base: optional, default empty string
59 :param inhibit_infer_root_dn: optional, default false
60 :returns: salt-specified state dict
61 """
62 test = __opts__['test'] # noqa
63 ret = {
64 'name': name,
65 'changes': {},
66 'result': False,
67 'comment': '',
68 }
69 result = False
70 if test:
71 status = 'CREATED'
72 ret['changes'][name] = status
73 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
74 else:
75 call_result = __salt__['jenkins_common.call_groovy_script'](
76 set_ldap_groovy, {"name": name, "server": server, "rootDN": root_dn,
Jakub Josef95ad9802017-01-17 15:59:00 +010077 "userSearchBase": user_search_base if user_search_base else "",
78 "managerDN": manager_dn if manager_dn else "",
79 "managerPassword": manager_password if manager_password else "",
80 "userSearch": user_search if user_search else "",
81 "groupSearchBase": group_search_base if group_search_base else "",
82 "inhibitInferRootDN": "true" if inhibit_infer_root_dn else "false"})
Jakub Josef063a7532017-01-11 15:48:01 +010083 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
84 status = call_result["msg"]
85 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +010086 ret['comment'] = 'Jenkins LDAP setting %s %s' % (
87 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +010088 result = True
89 else:
90 status = 'FAILED'
91 logger.error(
92 "Jenkins security API call failure: %s", call_result["msg"])
93 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +010094 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +010095 ret['result'] = None if test else result
96 return ret
97
Jakub Josef0ee470e2017-01-17 11:46:58 +010098
99def matrix(name, strategies, project_based=False):
Jakub Josef063a7532017-01-11 15:48:01 +0100100 """
101 Jenkins matrix security state method
102
103 :param name: ldap state name
Jakub Josef0ee470e2017-01-17 11:46:58 +0100104 :param strategies: dict with matrix strategies
105 :param procect_based: flag if we configuring
106 GlobalMatrix security or ProjectMatrix security
Jakub Josef063a7532017-01-11 15:48:01 +0100107 :returns: salt-specified state dict
108 """
109 test = __opts__['test'] # noqa
110 ret = {
111 'name': name,
112 'changes': {},
113 'result': False,
114 'comment': '',
115 }
116 result = False
117 if test:
118 status = 'CREATED'
119 ret['changes'][name] = status
120 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
121 else:
122 call_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josef0ee470e2017-01-17 11:46:58 +0100123 set_matrix_groovy, {"strategies": _build_strategies(strategies),
124 "matrix_class": "ProjectMatrixAuthorizationStrategy" if project_based else "GlobalMatrixAuthorizationStrategy"})
Jakub Josef063a7532017-01-11 15:48:01 +0100125 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
126 status = call_result["msg"]
127 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +0100128 ret['comment'] = 'Jenkins Matrix security setting %s %s' % (
129 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +0100130 result = True
131 else:
132 status = 'FAILED'
133 logger.error(
134 "Jenkins security API call failure: %s", call_result["msg"])
135 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +0100136 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +0100137 ret['result'] = None if test else result
138 return ret
139
140
141def _build_strategies(permissions):
142 strategies_str = ""
143 for strategy in _to_strategies_list("strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
144 strategies_str += "{}\n".format(strategy)
145 return strategies_str
146
147
148def _to_strategies_list(strategy_format, strategy_dict):
149 res = []
150 for key, value in strategy_dict.items():
151 if isinstance(value, list):
152 for user in value:
153 res.append(strategy_format.format(key, user))
154 else:
155 res.append(strategy_format.format(key, value))
156 return res
157
158
159def _to_one_dict(input_dict, input_key):
160 res = {}
161 for key, value in input_dict.items():
162 new_key = key if input_key == "" else "{}.{}".format(input_key, key)
163 if isinstance(value, dict):
164 res.update(_to_one_dict(value, new_key))
165 else:
166 res[new_key] = value
167 return res