forked from jenkinsci/jenkins
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathUser.java
More file actions
1352 lines (1215 loc) · 49.5 KB
/
User.java
File metadata and controls
1352 lines (1215 loc) · 49.5 KB
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
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* The MIT License
*
* Copyright (c) 2004-2018, Sun Microsystems, Inc., Kohsuke Kawaguchi, Erik Ramfelt,
* Tom Huybrechts, Vincent Latombe, CloudBees, Inc.
*
* 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.model;
import com.infradna.tool.bridge_method_injector.WithBridgeMethods;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
import hudson.BulkChange;
import hudson.CopyOnWrite;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.XmlFile;
import hudson.init.InitMilestone;
import hudson.init.Initializer;
import hudson.model.listeners.SaveableListener;
import hudson.security.ACL;
import hudson.security.AccessControlled;
import hudson.security.SecurityRealm;
import hudson.security.UserMayOrMayNotExistException2;
import hudson.tasks.UserAvatarResolver;
import hudson.util.FormValidation;
import hudson.util.RunList;
import hudson.util.XStream2;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.function.Predicate;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import jenkins.model.IdStrategy;
import jenkins.model.Jenkins;
import jenkins.model.Loadable;
import jenkins.model.ModelObjectWithContextMenu;
import jenkins.scm.RunWithSCM;
import jenkins.search.SearchGroup;
import jenkins.security.HMACConfidentialKey;
import jenkins.security.ImpersonatingUserDetailsService2;
import jenkins.security.LastGrantedAuthoritiesProperty;
import jenkins.security.UserDetailsCache;
import jenkins.util.SystemProperties;
import org.jenkinsci.Symbol;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.Beta;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.StaplerProxy;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
import org.kohsuke.stapler.export.Exported;
import org.kohsuke.stapler.export.ExportedBean;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
/**
* Represents a user.
*
* <p>
* In Hudson, {@link User} objects are created in on-demand basis;
* for example, when a build is performed, its change log is computed
* and as a result commits from users who Hudson has never seen may be discovered.
* When this happens, new {@link User} object is created.
*
* <p>
* If the persisted record for an user exists, the information is loaded at
* that point, but if there's no such record, a fresh instance is created from
* thin air (this is where {@link UserPropertyDescriptor#newInstance(User)} is
* called to provide initial {@link UserProperty} objects.
*
* <p>
* Such newly created {@link User} objects will be simply GC-ed without
* ever leaving the persisted record, unless {@link User#save()} method
* is explicitly invoked (perhaps as a result of a browser submitting a
* configuration.)
*
* @author Kohsuke Kawaguchi
*/
@ExportedBean
public class User extends AbstractModelObject implements AccessControlled, DescriptorByNameOwner, Loadable, Saveable, Comparable<User>, ModelObjectWithContextMenu, StaplerProxy {
public static final XStream2 XSTREAM = new XStream2();
private static final Logger LOGGER = Logger.getLogger(User.class.getName());
static final String CONFIG_XML = "config.xml";
/**
* Escape hatch for StaplerProxy-based access control
*/
@Restricted(NoExternalUse.class)
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console")
public static /* Script Console modifiable */ boolean SKIP_PERMISSION_CHECK = SystemProperties.getBoolean(User.class.getName() + ".skipPermissionCheck");
/**
* Jenkins now refuses to let the user login if he/she doesn't exist in {@link SecurityRealm},
* which was necessary to make sure users removed from the backend will get removed from the frontend.
* <p>
* Unfortunately this infringed some legitimate use cases of creating Jenkins-local users for
* automation purposes. This escape hatch switch can be enabled to resurrect that behaviour.
* <p>
* See <a href="https://issues.jenkins.io/browse/JENKINS-22346">JENKINS-22346</a>.
*/
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console")
public static boolean ALLOW_NON_EXISTENT_USER_TO_LOGIN = SystemProperties.getBoolean(User.class.getName() + ".allowNonExistentUserToLogin");
/**
* Jenkins historically created a (usually) ephemeral user record when an user with Overall/Administer permission
* accesses a /user/arbitraryName URL.
* <p>
* Unfortunately this constitutes a CSRF vulnerability, as malicious users can make admins create arbitrary numbers
* of ephemeral user records, so the behavior was changed in Jenkins 2.44 / 2.32.2.
* <p>
* As some users may be relying on the previous behavior, setting this to true restores the previous behavior. This
* is not recommended.
* <p>
* SECURITY-406.
*/
@Restricted(NoExternalUse.class)
@SuppressFBWarnings(value = "MS_SHOULD_BE_FINAL", justification = "for script console")
public static boolean ALLOW_USER_CREATION_VIA_URL = SystemProperties.getBoolean(User.class.getName() + ".allowUserCreationViaUrl");
/**
* The username of the 'unknown' user used to avoid null user references.
*/
private static final String UNKNOWN_USERNAME = "unknown";
/**
* These usernames should not be used by real users logging into Jenkins. Therefore, we prevent
* users with these names from being saved.
*/
private static final String[] ILLEGAL_PERSISTED_USERNAMES = new String[]{ACL.ANONYMOUS_USERNAME,
ACL.SYSTEM_USERNAME, UNKNOWN_USERNAME};
@SuppressFBWarnings(value = "SS_SHOULD_BE_STATIC", justification = "Reserved for future use")
private final int version = 10; // Not currently used, but it may be helpful in the future to store a version.
String id;
private volatile String fullName;
private volatile String description;
@CopyOnWrite
private volatile List<UserProperty> properties = new ArrayList<>();
static {
XSTREAM.alias("user", User.class);
}
private User() {}
private User(String id, String fullName) {
this.id = id;
this.fullName = fullName;
load(id);
}
@Override
public void load() {
load(id);
}
private void load(String userId) {
clearExistingProperties();
loadFromUserConfigFile(userId);
fixUpAfterLoad();
}
private void fixUpAfterLoad() {
removeNullsThatFailedToLoad();
allocateDefaultPropertyInstancesAsNeeded();
setUserToProperties();
}
private void setUserToProperties() {
for (UserProperty p : properties) {
p.setUser(this);
}
}
private void allocateDefaultPropertyInstancesAsNeeded() {
for (UserPropertyDescriptor d : UserProperty.all()) {
if (getProperty(d.clazz) == null) {
UserProperty up = d.newInstance(this);
if (up != null)
properties.add(up);
}
}
}
private void removeNullsThatFailedToLoad() {
properties.removeIf(Objects::isNull);
}
private void loadFromUserConfigFile(String userId) {
AllUsers.getInstance().migrateUserIdMapper();
XmlFile config = getConfigFile();
try {
if (config.exists()) {
config.unmarshal(this);
this.id = userId;
}
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to load " + config, e);
}
}
private void clearExistingProperties() {
properties.clear();
}
private XmlFile getConfigFile() {
return new XmlFile(XSTREAM, new File(getUserFolderFor(id), CONFIG_XML));
}
/**
* Returns the {@link jenkins.model.IdStrategy} for use with {@link User} instances. See
* {@link hudson.security.SecurityRealm#getUserIdStrategy()}
*
* @return the {@link jenkins.model.IdStrategy} for use with {@link User} instances.
* @since 1.566
*/
@NonNull
public static IdStrategy idStrategy() {
Jenkins j = Jenkins.get();
SecurityRealm realm = j.getSecurityRealm();
if (realm == null) {
return IdStrategy.CASE_INSENSITIVE;
}
return realm.getUserIdStrategy();
}
@Override
public int compareTo(@NonNull User that) {
return idStrategy().compare(this.id, that.id);
}
@Exported
public String getId() {
return id;
}
public @NonNull String getUrl() {
return "user/" + Util.rawEncode(idStrategy().keyFor(id));
}
@Override
public @NonNull String getSearchUrl() {
return "/user/" + Util.rawEncode(idStrategy().keyFor(id));
}
@Override
public String getSearchIcon() {
return UserAvatarResolver.resolve(this, "48x48");
}
@Override
public SearchGroup getSearchGroup() {
return SearchGroup.get(SearchGroup.UserSearchGroup.class);
}
/**
* The URL of the user page.
*/
@Exported(visibility = 999)
public @NonNull String getAbsoluteUrl() {
return Jenkins.get().getRootUrl() + getUrl();
}
/**
* Gets the human readable name of this user.
* This is configurable by the user.
*/
@Exported(visibility = 999)
public @NonNull String getFullName() {
return fullName;
}
/**
* Sets the human readable name of the user.
* If the input parameter is empty, the user's ID will be set.
*/
public void setFullName(String name) {
if (Util.fixEmptyAndTrim(name) == null) name = id;
this.fullName = name;
}
@Exported
public @CheckForNull String getDescription() {
return description;
}
/**
* Sets the description of the user.
*
* @since 1.609
*/
public void setDescription(String description) {
this.description = description;
}
/**
* Gets the user properties configured for this user.
*/
public Map<Descriptor<UserProperty>, UserProperty> getProperties() {
return Descriptor.toMap(properties);
}
/**
* Updates the user object by adding a property.
*/
public synchronized void addProperty(@NonNull UserProperty p) throws IOException {
UserProperty old = getProperty(p.getClass());
List<UserProperty> ps = new ArrayList<>(properties);
if (old != null)
ps.remove(old);
ps.add(p);
p.setUser(this);
properties = ps;
save();
}
/**
* Expand {@link #addProperty(UserProperty)} for multiple properties to be done at once.
* Expected to be used by the categorized configuration pages to update part of the properties.
* The properties not included in the list will be let untouched.
* It will call the {@link UserProperty#setUser(User)} method and at the end, {@link #save()} once.
*
* @since 2.468
*/
public synchronized void addProperties(@NonNull List<UserProperty> multipleProperties) throws IOException {
List<UserProperty> newProperties = new ArrayList<>(this.properties);
for (UserProperty property : multipleProperties) {
UserProperty oldProp = getProperty(property.getClass());
if (oldProp != null) {
newProperties.remove(oldProp);
}
newProperties.add(property);
property.setUser(this);
}
this.properties = newProperties;
this.save();
}
/**
* List of all {@link UserProperty}s exposed primarily for the remoting API.
*/
@Exported(name = "property", inline = true)
public List<UserProperty> getAllProperties() {
if (hasPermission(Jenkins.ADMINISTER)) {
return Collections.unmodifiableList(properties);
}
return Collections.emptyList();
}
/**
* Gets the specific property, or null.
*/
public <T extends UserProperty> T getProperty(Class<T> clazz) {
for (UserProperty p : properties) {
if (clazz.isInstance(p))
return clazz.cast(p);
}
return null;
}
/**
* Creates an {@link Authentication} object that represents this user.
* <p>
* This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm.
* If {@link SecurityRealm} is a kind that does not support querying information about other users, this will
* use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has
* logged in.
*
* @throws UsernameNotFoundException If this user is not a valid user in the backend {@link SecurityRealm}.
* @since 2.266
*/
public @NonNull Authentication impersonate2() throws UsernameNotFoundException {
return this.impersonate(this.getUserDetailsForImpersonation2());
}
/**
* @deprecated use {@link #impersonate2}
* @since 1.419
*/
@Deprecated
public @NonNull org.acegisecurity.Authentication impersonate() throws org.acegisecurity.userdetails.UsernameNotFoundException {
try {
return org.acegisecurity.Authentication.fromSpring(impersonate2());
} catch (AuthenticationException x) {
throw org.acegisecurity.AuthenticationException.fromSpring(x);
}
}
/**
* This method checks with {@link SecurityRealm} if the user is a valid user that can login to the security realm.
* If {@link SecurityRealm} is a kind that does not support querying information about other users, this will
* use {@link LastGrantedAuthoritiesProperty} to pick up the granted authorities as of the last time the user has
* logged in.
*
* @return userDetails for the user, in case he's not found but seems legitimate, we provide a userDetails with minimum access
* @throws UsernameNotFoundException If this user is not a valid user in the backend {@link SecurityRealm}.
* @since 2.266
*/
public @NonNull UserDetails getUserDetailsForImpersonation2() throws UsernameNotFoundException {
ImpersonatingUserDetailsService2 userDetailsService = new ImpersonatingUserDetailsService2(
Jenkins.get().getSecurityRealm().getSecurityComponents().userDetails2
);
try {
UserDetails userDetails = userDetailsService.loadUserByUsername(id);
LOGGER.log(Level.FINE, "Impersonation of the user {0} was a success", id);
return userDetails;
} catch (UserMayOrMayNotExistException2 e) {
LOGGER.log(Level.FINE, "The user {0} may or may not exist in the SecurityRealm, so we provide minimum access", id);
} catch (UsernameNotFoundException e) {
if (ALLOW_NON_EXISTENT_USER_TO_LOGIN) {
LOGGER.log(Level.FINE, "The user {0} was not found in the SecurityRealm but we are required to let it pass, due to ALLOW_NON_EXISTENT_USER_TO_LOGIN", id);
} else {
LOGGER.log(Level.FINE, "The user {0} was not found in the SecurityRealm", id);
throw e;
}
}
return new LegitimateButUnknownUserDetails(id);
}
/**
* @deprecated use {@link #getUserDetailsForImpersonation2}
*/
@Deprecated
public @NonNull org.acegisecurity.userdetails.UserDetails getUserDetailsForImpersonation() throws org.acegisecurity.userdetails.UsernameNotFoundException {
try {
return org.acegisecurity.userdetails.UserDetails.fromSpring(getUserDetailsForImpersonation2());
} catch (AuthenticationException x) {
throw org.acegisecurity.AuthenticationException.fromSpring(x);
}
}
/**
* Only used for a legitimate user we have no idea about. We give it only minimum access
*/
private static class LegitimateButUnknownUserDetails extends org.springframework.security.core.userdetails.User {
private LegitimateButUnknownUserDetails(String username) throws IllegalArgumentException {
super(
username, "",
true, true, true, true,
Set.of(SecurityRealm.AUTHENTICATED_AUTHORITY2)
);
}
}
/**
* Creates an {@link Authentication} object that represents this user using the given userDetails
*
* @param userDetails Provided by {@link #getUserDetailsForImpersonation2()}.
* @see #getUserDetailsForImpersonation2()
*/
@Restricted(NoExternalUse.class)
public @NonNull Authentication impersonate(@NonNull UserDetails userDetails) {
return new UsernamePasswordAuthenticationToken(userDetails.getUsername(), "", userDetails.getAuthorities());
}
/**
* Accepts the new description.
*/
@RequirePOST
public void doSubmitDescription(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
description = req.getParameter("description");
save();
rsp.sendRedirect("."); // go to the top page
}
/**
* Gets the fallback "unknown" user instance.
* <p>
* This is used to avoid null {@link User} instance.
*/
public static @NonNull User getUnknown() {
return getById(UNKNOWN_USERNAME, true);
}
/**
* Gets the {@link User} object by its id or full name.
*
* @param create If true, this method will never return null for valid input
* (by creating a new {@link User} object if none exists.)
* If false, this method will return null if {@link User} object
* with the given name doesn't exist.
* @return Requested user. May be {@code null} if a user does not exist and
* {@code create} is false.
* @deprecated use {@link User#get(String, boolean, java.util.Map)}
*/
@Deprecated
public static @Nullable User get(String idOrFullName, boolean create) {
return get(idOrFullName, create, Collections.emptyMap());
}
/**
* Gets the {@link User} object by its id or full name.
* <p>
* In order to resolve the user ID, the method invokes {@link CanonicalIdResolver} extension points.
* Note that it may cause significant performance degradation.
* If you are sure the passed value is a User ID, it is recommended to use {@link #getById(String, boolean)}.
*
* @param create If true, this method will never return null for valid input
* (by creating a new {@link User} object if none exists.)
* If false, this method will return null if {@link User} object
* with the given name doesn't exist.
* @param context contextual environment this user idOfFullName was retrieved from,
* that can help resolve the user ID
* @return An existing or created user. May be {@code null} if a user does not exist and
* {@code create} is false.
*/
public static @Nullable User get(String idOrFullName, boolean create, @NonNull Map context) {
if (idOrFullName == null) {
return null;
}
User user = AllUsers.get(idOrFullName);
if (user != null) {
return user;
}
String id = CanonicalIdResolver.resolve(idOrFullName, context);
return getOrCreateById(id, idOrFullName, create);
}
/**
* Retrieve a user by its ID, and create a new one if requested.
*
* @return An existing or created user. May be {@code null} if a user does not exist and
* {@code create} is false.
*/
private static @Nullable User getOrCreateById(@NonNull String id, @NonNull String fullName, boolean create) {
User u = AllUsers.get(id);
if (u == null && create) {
u = new User(id, fullName);
AllUsers.put(id, u);
if (!id.equals(fullName)) {
try {
u.save();
} catch (IOException x) {
LOGGER.log(Level.WARNING, "Failed to save user configuration for " + id, x);
}
}
}
return u;
}
/**
* Gets the {@link User} object by its id or full name.
* <p>
* Creates a user on-demand.
*
* <p>
* Use {@link #getById} when you know you have an ID.
* In this method Jenkins will try to resolve the {@link User} by full name with help of various
* {@link hudson.tasks.UserNameResolver}.
* This is slow (see JENKINS-23281).
*
* @deprecated This method is deprecated, because it causes unexpected {@link User} creation
* by API usage code and causes performance degradation of used to retrieve users by ID.
* Use {@link #getById} when you know you have an ID.
* Otherwise use {@link #getOrCreateByIdOrFullName(String)} or {@link #get(String, boolean, Map)}.
*/
@Deprecated
public static @NonNull User get(String idOrFullName) {
return getOrCreateByIdOrFullName(idOrFullName);
}
/**
* Get the user by ID or Full Name.
* <p>
* If the user does not exist, creates a new one on-demand.
*
* <p>
* Use {@link #getById} when you know you have an ID.
* In this method Jenkins will try to resolve the {@link User} by full name with help of various
* {@link hudson.tasks.UserNameResolver}.
* This is slow (see JENKINS-23281).
*
* @param idOrFullName User ID or full name
* @return User instance. It will be created on-demand.
* @since 2.91
*/
public static @NonNull User getOrCreateByIdOrFullName(@NonNull String idOrFullName) {
return get(idOrFullName, true, Collections.emptyMap());
}
/**
* Gets the {@link User} object representing the currently logged-in user, or null
* if the current user is anonymous.
*
* @since 1.172
*/
public static @CheckForNull User current() {
return get2(Jenkins.getAuthentication2());
}
/**
* Gets the {@link User} object representing the supplied {@link Authentication} or
* {@code null} if the supplied {@link Authentication} is either anonymous or {@code null}
*
* @param a the supplied {@link Authentication} .
* @return a {@link User} object for the supplied {@link Authentication} or {@code null}
* @since 2.266
*/
public static @CheckForNull User get2(@CheckForNull Authentication a) {
if (a == null || a instanceof AnonymousAuthenticationToken)
return null;
// Since we already know this is a name, we can just call getOrCreateById with the name directly.
return getById(a.getName(), true);
}
/**
* @deprecated use {@link #get2(Authentication)}
* @since 1.609
*/
@Deprecated
public static @CheckForNull User get(@CheckForNull org.acegisecurity.Authentication a) {
return get2(a != null ? a.toSpring() : null);
}
/**
* Gets the {@link User} object by its {@code id}
*
* @param id the id of the user to retrieve and optionally create if it does not exist.
* @param create If {@code true}, this method will never return {@code null} for valid input (by creating a
* new {@link User} object if none exists.) If {@code false}, this method will return
* {@code null} if {@link User} object with the given id doesn't exist.
* @return the a User whose id is {@code id}, or {@code null} if {@code create} is {@code false}
* and the user does not exist.
* @since 1.651.2 / 2.3
*/
public static @Nullable User getById(String id, boolean create) {
return getOrCreateById(id, id, create);
}
/**
* Gets all the users.
*/
public static @NonNull Collection<User> getAll() {
final IdStrategy strategy = idStrategy();
ArrayList<User> users = new ArrayList<>(AllUsers.values());
users.sort((o1, o2) -> strategy.compare(o1.getId(), o2.getId()));
return users;
}
/**
* Called from {@link Jenkins#reload}.
*/
@Restricted(Beta.class)
public static void reload() throws IOException {
AllUsers.reload();
}
/**
* Called when changing the {@link IdStrategy}.
*
* @since 1.566
*/
public static void rekey() {
/* There are many and varied ways in which this could cause erratic or
problematic behavior. Such changes should really only occur during initial
setup and under very controlled situations. After this sort of a change
the whole webapp should restart. It's possible that this rekeying,
or greater issues in the realm change, could affect currently logged
in users and even the user making the change. */
try {
var subdirectories = getRootDir().listFiles();
if (subdirectories != null) {
for (var oldDirectory : subdirectories) {
var dirName = oldDirectory.getName();
if (!HASHED_DIRNAMES.matcher(dirName).matches()) {
continue;
}
var xml = new XmlFile(XSTREAM, new File(oldDirectory, CONFIG_XML));
if (!xml.exists()) {
continue;
}
try {
var user = (User) xml.read();
if (user.id == null) {
continue;
}
var newDirectory = getUserFolderFor(user.id);
if (!oldDirectory.equals(newDirectory)) {
Files.move(oldDirectory.toPath(), newDirectory.toPath(), StandardCopyOption.REPLACE_EXISTING);
LOGGER.info(() -> "migrated " + oldDirectory + " to " + newDirectory);
}
} catch (Exception x) {
LOGGER.log(Level.WARNING, "failed to migrate " + xml, x);
}
}
}
reload();
} catch (IOException e) {
LOGGER.log(Level.SEVERE, "Failed to perform rekey operation.", e);
}
}
/**
* Returns the user name.
*/
@Override
public @NonNull String getDisplayName() {
return getFullName();
}
/**
* true if {@link RunWithSCM#hasParticipant} or {@link hudson.model.Cause.UserIdCause}
*/
private boolean relatedTo(@NonNull Run<?, ?> b) {
if (b instanceof RunWithSCM && ((RunWithSCM) b).hasParticipant(this)) {
return true;
}
for (Cause cause : b.getCauses()) {
if (cause instanceof Cause.UserIdCause) {
String userId = ((Cause.UserIdCause) cause).getUserId();
if (userId != null && idStrategy().equals(userId, getId())) {
return true;
}
}
}
return false;
}
/**
* Searches for builds which include changes by this user or which were triggered by this user.
*/
@SuppressWarnings("unchecked")
@WithBridgeMethods(List.class)
public @NonNull RunList getBuilds() {
return RunList.fromJobs((Iterable) Jenkins.get().
allItems(Job.class)).filter((Predicate<Run<?, ?>>) this::relatedTo);
}
/**
* Gets all the {@link AbstractProject}s that this user has committed to.
*
* @since 1.191
*/
public @NonNull Set<AbstractProject<?, ?>> getProjects() {
Set<AbstractProject<?, ?>> r = new HashSet<>();
for (AbstractProject<?, ?> p : Jenkins.get().allItems(AbstractProject.class, p -> p.hasParticipant(this)))
r.add(p);
return r;
}
@Override
public String toString() {
return id;
}
/**
* Called by tests in the JTH. Otherwise this shouldn't be called.
* Even in the tests this usage is questionable.
* @deprecated removed without replacement
*/
@Deprecated
public static void clear() {
if (ExtensionList.lookup(AllUsers.class).isEmpty()) {
return;
}
AllUsers.clear();
}
/**
* Returns the folder that store all the user information.
* Useful for plugins to save a user-specific file aside the config.xml.
* Exposes implementation details that may be subject to change.
*
* @return The folder containing the user configuration files or {@code null} if the user was not yet saved.
*
* @since 2.129
*/
public @CheckForNull File getUserFolder() {
var d = getUserFolderFor(id);
return d.isDirectory() ? d : null;
}
/**
* Gets the directory where Hudson stores user information.
*/
static File getRootDir() {
return new File(Jenkins.get().getRootDir(), "users");
}
private static final int PREFIX_MAX = 14;
private static final Pattern DISALLOWED_PREFIX_CHARS = Pattern.compile("[^A-Za-z0-9]");
static final Pattern HASHED_DIRNAMES = Pattern.compile("[a-z0-9]{0," + PREFIX_MAX + "}_[a-f0-9]{64}");
private static final HMACConfidentialKey DIRNAMES = new HMACConfidentialKey(User.class, "DIRNAMES");
private static String getUserFolderNameFor(String id) {
var fullPrefix = DISALLOWED_PREFIX_CHARS.matcher(id).replaceAll("").toLowerCase(Locale.ROOT);
return (fullPrefix.length() > PREFIX_MAX ? fullPrefix.substring(0, PREFIX_MAX) : fullPrefix) + '_' + DIRNAMES.mac(idStrategy().keyFor(id));
}
@SuppressFBWarnings(value = "PATH_TRAVERSAL_IN", justification = "sanitized")
static File getUserFolderFor(String id) {
return new File(getRootDir(), getUserFolderNameFor(id));
}
/**
* Is the ID allowed? Some are prohibited for security reasons. See SECURITY-166.
* <p>
* Note that this is only enforced when saving. These users are often created
* via the constructor (and even listed on /asynchPeople), but our goal is to
* prevent anyone from logging in as these users. Therefore, we prevent
* saving a User with one of these ids.
*
* @param id ID to be checked
* @return {@code true} if the username or fullname is valid.
* For {@code null} or blank IDs returns {@code false}.
* @since 1.600
*/
public static boolean isIdOrFullnameAllowed(@CheckForNull String id) {
if (id == null || id.isBlank()) {
return false;
}
final String trimmedId = id.trim();
for (String invalidId : ILLEGAL_PERSISTED_USERNAMES) {
if (trimmedId.equalsIgnoreCase(invalidId))
return false;
}
return true;
}
/**
* Save the user configuration.
*/
@Override
public synchronized void save() throws IOException {
if (!isIdOrFullnameAllowed(id)) {
throw FormValidation.error(Messages.User_IllegalUsername(id));
}
if (!isIdOrFullnameAllowed(fullName)) {
throw FormValidation.error(Messages.User_IllegalFullname(fullName));
}
if (BulkChange.contains(this)) {
return;
}
XmlFile xmlFile = getConfigFile();
xmlFile.write(this);
SaveableListener.fireOnChange(this, xmlFile);
}
/**
* Deletes the data directory and removes this user from Hudson.
*
* @throws IOException if we fail to delete.
*/
public void delete() throws IOException {
String idKey = idStrategy().keyFor(id);
AllUsers.remove(id);
Util.deleteRecursive(getUserFolderFor(id));
UserDetailsCache.get().invalidate(idKey);
}
/**
* Exposed remote API.
*/
public Api getApi() {
return new Api(this);
}
/**
* Deletes this user from Hudson.
*/
@RequirePOST
public void doDoDelete(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException {
checkPermission(Jenkins.ADMINISTER);
if (idStrategy().equals(id, Jenkins.getAuthentication2().getName())) {
rsp.sendError(HttpServletResponse.SC_BAD_REQUEST, "Cannot delete self");
return;
}
delete();
rsp.sendRedirect2("../..");
}
public void doRssAll(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (all builds)", getUrl(), getBuilds().newBuilds());
}
public void doRssFailed(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (failed builds)", getUrl(), getBuilds().regressionOnly());
}
public void doRssLatest(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
final List<Run> lastBuilds = new ArrayList<>();
for (Job<?, ?> p : Jenkins.get().allItems(Job.class)) {
for (Run<?, ?> b = p.getLastBuild(); b != null; b = b.getPreviousBuild()) {
if (relatedTo(b)) {
lastBuilds.add(b);
break;
}
}
}
// historically these have been reported sorted by project name, we switched to the lazy iteration
// so we only have to sort the sublist of runs rather than the full list of irrelevant projects
lastBuilds.sort((o1, o2) -> Items.BY_FULL_NAME.compare(o1.getParent(), o2.getParent()));
RSS.rss(req, rsp, "Jenkins:" + getDisplayName() + " (latest builds)", getUrl(), RunList.fromRuns(lastBuilds), Run.FEED_ADAPTER_LATEST);
}
@Override
@NonNull
public ACL getACL() {
ACL base = Jenkins.get().getAuthorizationStrategy().getACL(this);
// always allow a non-anonymous user full control of himself.
return ACL.lambda2((a, permission) -> (idStrategy().equals(a.getName(), id) && !(a instanceof AnonymousAuthenticationToken))
|| base.hasPermission2(a, permission));
}
/**
* With ADMINISTER permission, can delete users with persisted data but can't delete self.
*/
public boolean canDelete() {
final IdStrategy strategy = idStrategy();
return hasPermission(Jenkins.ADMINISTER) && !strategy.equals(id, Jenkins.getAuthentication2().getName())
&& getUserFolder() != null;
}
/**
* Checks for authorities (groups) associated with this user.
* If the caller lacks {@link Jenkins#ADMINISTER}, or any problems arise, returns an empty list.
* {@link SecurityRealm#AUTHENTICATED_AUTHORITY2} and the username, if present, are omitted.
*
* @return a possibly empty list
* @since 1.498
*/
public @NonNull List<String> getAuthorities() {
if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
return Collections.emptyList();
}
List<String> r = new ArrayList<>();
Authentication authentication;
try {
authentication = impersonate2();
} catch (UsernameNotFoundException x) {
LOGGER.log(Level.FINE, "cannot look up authorities for " + id, x);
return Collections.emptyList();
}
for (GrantedAuthority a : authentication.getAuthorities()) {
if (a.equals(SecurityRealm.AUTHENTICATED_AUTHORITY2)) {
continue;
}