blob: 299c974b031d4dd9ef5484309b0eec3eae5f39fa [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,
77 "userSearchBase": user_search_base, "managerDN": manager_dn, "managerPassword": manager_password, "userSearch": user_search if user_search else "", "groupSearchBase": group_search_base if group_search_base else "", "inhibitInferRootDN": "true" if inhibit_infer_root_dn else "false"})
78 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
79 status = call_result["msg"]
80 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +010081 ret['comment'] = 'Jenkins LDAP setting %s %s' % (
82 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +010083 result = True
84 else:
85 status = 'FAILED'
86 logger.error(
87 "Jenkins security API call failure: %s", call_result["msg"])
88 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +010089 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +010090 ret['result'] = None if test else result
91 return ret
92
Jakub Josef0ee470e2017-01-17 11:46:58 +010093
94def matrix(name, strategies, project_based=False):
Jakub Josef063a7532017-01-11 15:48:01 +010095 """
96 Jenkins matrix security state method
97
98 :param name: ldap state name
Jakub Josef0ee470e2017-01-17 11:46:58 +010099 :param strategies: dict with matrix strategies
100 :param procect_based: flag if we configuring
101 GlobalMatrix security or ProjectMatrix security
Jakub Josef063a7532017-01-11 15:48:01 +0100102 :returns: salt-specified state dict
103 """
104 test = __opts__['test'] # noqa
105 ret = {
106 'name': name,
107 'changes': {},
108 'result': False,
109 'comment': '',
110 }
111 result = False
112 if test:
113 status = 'CREATED'
114 ret['changes'][name] = status
115 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
116 else:
117 call_result = __salt__['jenkins_common.call_groovy_script'](
Jakub Josef0ee470e2017-01-17 11:46:58 +0100118 set_matrix_groovy, {"strategies": _build_strategies(strategies),
119 "matrix_class": "ProjectMatrixAuthorizationStrategy" if project_based else "GlobalMatrixAuthorizationStrategy"})
Jakub Josef063a7532017-01-11 15:48:01 +0100120 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
121 status = call_result["msg"]
122 ret['changes'][name] = status
Jakub Josef0ee470e2017-01-17 11:46:58 +0100123 ret['comment'] = 'Jenkins Matrix security setting %s %s' % (
124 name, status.lower())
Jakub Josef063a7532017-01-11 15:48:01 +0100125 result = True
126 else:
127 status = 'FAILED'
128 logger.error(
129 "Jenkins security API call failure: %s", call_result["msg"])
130 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
Jakub Josef0ee470e2017-01-17 11:46:58 +0100131 "msg"])
Jakub Josef063a7532017-01-11 15:48:01 +0100132 ret['result'] = None if test else result
133 return ret
134
135
136def _build_strategies(permissions):
137 strategies_str = ""
138 for strategy in _to_strategies_list("strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
139 strategies_str += "{}\n".format(strategy)
140 return strategies_str
141
142
143def _to_strategies_list(strategy_format, strategy_dict):
144 res = []
145 for key, value in strategy_dict.items():
146 if isinstance(value, list):
147 for user in value:
148 res.append(strategy_format.format(key, user))
149 else:
150 res.append(strategy_format.format(key, value))
151 return res
152
153
154def _to_one_dict(input_dict, input_key):
155 res = {}
156 for key, value in input_dict.items():
157 new_key = key if input_key == "" else "{}.{}".format(input_key, key)
158 if isinstance(value, dict):
159 res.update(_to_one_dict(value, new_key))
160 else:
161 res[new_key] = value
162 return res