blob: 24a8a6795998a056329314d342799afb563672c3 [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{{
36def strategy = Class.forName("hudson.security.ProjectMatrixAuthorizationStrategy").newInstance()
37{strategies}
38instance.setAuthorizationStrategy(strategy)
39instance.save()
40print("SUCCESS")
41}}catch(ClassNotFoundException e){{
42 print("Cannot instantiate ProjectMatrixAuthorizationStrategy, maybe auth-matrix plugin not installed")
43}}
44""" # noqa
45
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
81 ret['comment'] = 'Jenkins LDAP setting %s %s' % (name, status.lower())
82 result = True
83 else:
84 status = 'FAILED'
85 logger.error(
86 "Jenkins security API call failure: %s", call_result["msg"])
87 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
88 "msg"])
89 ret['result'] = None if test else result
90 return ret
91
92def matrix(name, strategies):
93 """
94 Jenkins matrix security state method
95
96 :param name: ldap state name
97 :param strategies: dict with matrix strategies
98 :returns: salt-specified state dict
99 """
100 test = __opts__['test'] # noqa
101 ret = {
102 'name': name,
103 'changes': {},
104 'result': False,
105 'comment': '',
106 }
107 result = False
108 if test:
109 status = 'CREATED'
110 ret['changes'][name] = status
111 ret['comment'] = 'LDAP setup %s %s' % (name, status.lower())
112 else:
113 call_result = __salt__['jenkins_common.call_groovy_script'](
114 set_matrix_groovy, {"strategies":_build_strategies(strategies)})
115 if call_result["code"] == 200 and call_result["msg"] == "SUCCESS":
116 status = call_result["msg"]
117 ret['changes'][name] = status
118 ret['comment'] = 'Jenkins Matrix security setting %s %s' % (name, status.lower())
119 result = True
120 else:
121 status = 'FAILED'
122 logger.error(
123 "Jenkins security API call failure: %s", call_result["msg"])
124 ret['comment'] = 'Jenkins security API call failure: %s' % (call_result[
125 "msg"])
126 ret['result'] = None if test else result
127 return ret
128
129
130def _build_strategies(permissions):
131 strategies_str = ""
132 for strategy in _to_strategies_list("strategy.add({},\"{}\")", _to_one_dict(permissions, "")):
133 strategies_str += "{}\n".format(strategy)
134 return strategies_str
135
136
137def _to_strategies_list(strategy_format, strategy_dict):
138 res = []
139 for key, value in strategy_dict.items():
140 if isinstance(value, list):
141 for user in value:
142 res.append(strategy_format.format(key, user))
143 else:
144 res.append(strategy_format.format(key, value))
145 return res
146
147
148def _to_one_dict(input_dict, input_key):
149 res = {}
150 for key, value in input_dict.items():
151 new_key = key if input_key == "" else "{}.{}".format(input_key, key)
152 if isinstance(value, dict):
153 res.update(_to_one_dict(value, new_key))
154 else:
155 res[new_key] = value
156 return res