/
ActiveDirectoryUserDetail.java
251 lines (221 loc) · 10.3 KB
/
ActiveDirectoryUserDetail.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
/*
* The MIT License
*
* Copyright (c) 2008-2014, Kohsuke Kawaguchi, CloudBees, Inc., and contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package hudson.plugins.active_directory;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import hudson.security.HudsonPrivateSecurityRealm;
import hudson.security.SecurityRealm;
import hudson.tasks.Mailer;
import hudson.tasks.Mailer.UserProperty;
import jenkins.model.Jenkins;
import org.acegisecurity.GrantedAuthority;
import org.acegisecurity.userdetails.User;
import org.acegisecurity.userdetails.UserDetails;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
/**
* @author Kohsuke Kawaguchi
*/
public class ActiveDirectoryUserDetail extends User {
// additional attributes from Active Directory
private final String displayName, mail, telephoneNumber;
private String toStringValue;
public ActiveDirectoryUserDetail(String username, String password,
boolean enabled, boolean accountNonExpired,
boolean credentialsNonExpired, boolean accountNonLocked,
GrantedAuthority[] authorities,
String displayName, String mail, String telephoneNumber)
throws IllegalArgumentException {
// Acegi doesn't like null password, but during remember-me processing
// we don't know the password so we need to set some dummy. See #1229
super(username, password != null ? password : "PASSWORD", enabled,
accountNonExpired, credentialsNonExpired, accountNonLocked,
authorities);
this.displayName = displayName;
this.mail = mail;
this.telephoneNumber = telephoneNumber;
}
public String getDisplayName() {
return displayName;
}
public String getMail() {
return mail;
}
public String getTelephoneNumber() {
return telephoneNumber;
}
@Override
public String toString() {
return toStringValue;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof ActiveDirectoryUserDetail)) return false;
if (!super.equals(o)) return false;
ActiveDirectoryUserDetail that = (ActiveDirectoryUserDetail)o;
if (displayName != null ? !displayName.equals(that.displayName) : that.displayName != null) {
return false;
}
if (mail != null ? !mail.equals(that.mail) : that.mail != null) {
return false;
}
if (telephoneNumber != null ? !telephoneNumber.equals(that.telephoneNumber) : that.telephoneNumber != null) {
return false;
}
return !(toStringValue != null ? !toStringValue.equals(that.toStringValue) : that.toStringValue != null);
}
@Override
public int hashCode() {
int result = super.hashCode();
result = 31 * result + (displayName != null ? displayName.hashCode() : 0);
result = 31 * result + (mail != null ? mail.hashCode() : 0);
result = 31 * result + (telephoneNumber != null ? telephoneNumber.hashCode() : 0);
result = 31 * result + (toStringValue != null ? toStringValue.hashCode() : 0);
return result;
}
@Override
@SuppressFBWarnings(value="NP_NULL_ON_SOME_PATH_FROM_RETURN_VALUE", justification="https://github.com/jenkinsci/jenkins/pull/2094")
protected void setAuthorities(GrantedAuthority[] authorities) {
final Jenkins jenkins = Jenkins.getActiveInstance();
SecurityRealm realm = jenkins.getSecurityRealm();
if ((realm instanceof ActiveDirectorySecurityRealm)) {
ActiveDirectorySecurityRealm activeDirectoryRealm = (ActiveDirectorySecurityRealm)realm;
if (activeDirectoryRealm.removeIrrelevantGroups) {
Set<String> referencedGroups = new HashSet<>();
for (String group : jenkins.getAuthorizationStrategy().getGroups()) {
referencedGroups.add(group.toLowerCase());
}
// We remove irrelevant groups only if the active AuthorizationStrategy has any referenced groups:
if (!referencedGroups.isEmpty()) {
List<GrantedAuthority> relevantGroups = new ArrayList<>();
for (GrantedAuthority group : authorities) {
String groupName = group.getAuthority();
if (groupName != null && referencedGroups.contains(groupName.toLowerCase())) {
relevantGroups.add(group);
}
}
authorities = relevantGroups.toArray(new GrantedAuthority[0]);
}
}
}
super.setAuthorities(authorities);
StringBuilder sb = new StringBuilder();
sb.append(super.toString()).append(": ");
sb.append("Username: ").append(getUsername()).append("; ");
sb.append("Password: [PROTECTED]; ");
sb.append("Enabled: ").append(isEnabled()).append("; ");
sb.append("AccountNonExpired: ").append(isAccountNonExpired()).append("; ");
sb.append("credentialsNonExpired: ").append(isCredentialsNonExpired()).append("; ");
sb.append("AccountNonLocked: ").append(isAccountNonLocked()).append("; ");
if (this.getAuthorities() != null) {
sb.append("Granted Authorities: ");
for (int i = 0; i < this.getAuthorities().length; i++) {
if (i > 0) {
sb.append(", ");
}
sb.append(this.getAuthorities()[i].toString());
}
} else {
sb.append("Not granted any authorities");
}
toStringValue = sb.toString();
}
public static long getSerialVersionUID() {
return serialVersionUID;
}
/**
* Gets the corresponding {@link hudson.model.User} object.
*/
public hudson.model.User getJenkinsUser() {
try { // TODO 1.651.2+ remove reflection
return (hudson.model.User) hudson.model.User.class.getMethod("getById", String.class, boolean.class).invoke(null, getUsername(), true);
} catch (InvocationTargetException e) {
if (e.getCause() instanceof RuntimeException) {
throw (RuntimeException)e.getCause();
}
// Only RuntimeException is expected
LOGGER.log(Level.WARNING, String.format("There was a problem obtaining the Jenkins user %s by Id", getUsername()), e);
} catch (NoSuchMethodException e) {
// fine, older baseline
} catch (Exception e) { // unexpected
LOGGER.log(Level.WARNING, String.format("There was a problem obtaining the Jenkins user %s by Id", getUsername()), e);
}
return hudson.model.User.get(getUsername());
}
/**
* Use the information to update the {@link hudson.model.User} object.
*
* @return this
*/
public UserDetails updateUserInfo() {
// the challenge here is to set the name if it's not set, but if the user overrides that
//
hudson.model.User u = getJenkinsUser();
if (getDisplayName()!=null && u.getId().equals(u.getFullName()))
u.setFullName(getDisplayName());
UserProperty existing = u.getProperty(UserProperty.class);
if (existing==null || !existing.hasExplicitlyConfiguredAddress()) {
try {
u.addProperty(new Mailer.UserProperty(getMail()));
} catch (IOException e) {
LOGGER.log(Level.WARNING, "Failed to associate the e-mail address", e);
}
}
return this;
}
/**
* Update the the password for the specified {@link hudson.model.User} in the Jenkins
* Internal User Database
*
*
*/
protected void updatePasswordInJenkinsInternalDatabase(String username, String password) {
LOGGER.log(Level.FINEST, String.format("Looking in Jenkins Internal Database for user %s", username));
hudson.model.User internalUser = hudson.model.User.get(username);
HudsonPrivateSecurityRealm.Details details = internalUser.getProperty(HudsonPrivateSecurityRealm.Details.class);
try {
Class[] paramString = new Class[1];
paramString[0] = String.class;
Class cls = Class.forName("hudson.security.HudsonPrivateSecurityRealm$Details");
Method method = cls.getDeclaredMethod("fromPlainPassword", paramString);
method.setAccessible(true);
Object object = method.invoke(details, password);
if (object instanceof HudsonPrivateSecurityRealm.Details) {
HudsonPrivateSecurityRealm.Details newDetails = (HudsonPrivateSecurityRealm.Details) object;
internalUser.addProperty(newDetails);
}
} catch (ClassNotFoundException | IOException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
LOGGER.log(Level.WARNING, String.format("Failed to update the password for user %s in the Jenkins Internal Database", username), e);
}
}
private static final long serialVersionUID = 1L;
private static final Logger LOGGER = Logger.getLogger(ActiveDirectoryUserDetail.class.getName());
}