-
Notifications
You must be signed in to change notification settings - Fork 247
/
Copy pathCredentialsProvider.java
1884 lines (1799 loc) · 92.3 KB
/
CredentialsProvider.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
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) 2011-2016, CloudBees, Inc., Stephen Connolly.
*
* 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 com.cloudbees.plugins.credentials;
import com.cloudbees.plugins.credentials.builds.CredentialsParameterBinding;
import com.cloudbees.plugins.credentials.builds.CredentialsParameterBinder;
import com.cloudbees.plugins.credentials.common.IdCredentials;
import com.cloudbees.plugins.credentials.domains.DomainRequirement;
import com.cloudbees.plugins.credentials.fingerprints.ItemCredentialsFingerprintFacet;
import com.cloudbees.plugins.credentials.fingerprints.NodeCredentialsFingerprintFacet;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import edu.umd.cs.findbugs.annotations.Nullable;
import hudson.BulkChange;
import hudson.DescriptorExtensionList;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.init.InitMilestone;
import hudson.model.Cause;
import hudson.model.Computer;
import hudson.model.ComputerSet;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.DescriptorVisibilityFilter;
import hudson.model.Fingerprint;
import hudson.model.Item;
import hudson.model.ItemGroup;
import hudson.model.Job;
import hudson.model.ModelObject;
import hudson.model.Node;
import hudson.model.Queue;
import hudson.model.Run;
import hudson.model.User;
import hudson.model.queue.Tasks;
import hudson.security.ACL;
import hudson.security.ACLContext;
import hudson.security.Permission;
import hudson.security.PermissionGroup;
import hudson.security.PermissionScope;
import hudson.security.SecurityRealm;
import hudson.util.ListBoxModel;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.nio.charset.StandardCharsets;
import java.security.DigestOutputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.Collator;
import java.util.AbstractMap;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import jenkins.model.FingerprintFacet;
import jenkins.model.Jenkins;
import jenkins.util.Timer;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.jenkins.ui.icon.IconSpec;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.stapler.Stapler;
import org.kohsuke.stapler.StaplerRequest2;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import static com.cloudbees.plugins.credentials.CredentialsStoreAction.FINGERPRINT_XML;
/**
* An extension point for providing {@link Credentials}.
*/
public abstract class CredentialsProvider extends Descriptor<CredentialsProvider>
implements ExtensionPoint, Describable<CredentialsProvider>, IconSpec {
/**
* A {@link CredentialsProvider} that does nothing for use as a marker
*
* @since 2.1.1
*/
public static final CredentialsProvider NONE = new CredentialsProvider() {};
/**
* The permission group for credentials.
*
* @since 1.8
*/
public static final PermissionGroup GROUP = new PermissionGroup(CredentialsProvider.class,
Messages._CredentialsProvider_PermissionGroupTitle());
/**
* Where an immediate action against a job requires that a credential be selected by the user triggering the
* action, this permission allows the user to select a credential from their private credential store. Immediate
* actions could include: building with parameters, tagging a build, deploying artifacts, etc.
*
* @since 1.16
*/
public static final Permission USE_OWN = new Permission(GROUP, "UseOwn",
Messages._CredentialsProvider_UseOwnPermissionDescription(),
Boolean.getBoolean("com.cloudbees.plugins.credentials.UseOwnPermission") ? Jenkins.ADMINISTER : Job.BUILD,
Boolean.getBoolean("com.cloudbees.plugins.credentials.UseOwnPermission"),
new PermissionScope[]{PermissionScope.ITEM});
/**
* Where an immediate action against a job requires that a credential be selected by the user triggering the
* action, this permission allows the user to select a credential from those credentials available within the
* scope of the job. Immediate actions could include: building with parameters, tagging a build,
* deploying artifacts, etc.
*
* This permission is implied by {@link Job#CONFIGURE} as anyone who can configure the job can configure the
* job to use credentials within the item scope anyway.
*
* @since 1.16
*/
public static final Permission USE_ITEM = new Permission(GROUP, "UseItem",
Messages._CredentialsProvider_UseItemPermissionDescription(), Job.CONFIGURE,
Boolean.getBoolean("com.cloudbees.plugins.credentials.UseItemPermission"),
new PermissionScope[]{PermissionScope.ITEM});
/**
* Our logger.
*
* @since 1.6
*/
private static final Logger LOGGER = Logger.getLogger(CredentialsProvider.class.getName());
/**
* The scopes that we allow credential permissions on.
*
* @since 1.12.
*/
private static final PermissionScope[] SCOPES =
new PermissionScope[]{PermissionScope.ITEM, PermissionScope.ITEM_GROUP, PermissionScope.JENKINS};
/**
* The permission for adding credentials to a {@link CredentialsStore}.
*
* @since 1.8
*/
public static final Permission CREATE = new Permission(GROUP, "Create",
Messages._CredentialsProvider_CreatePermissionDescription(), Permission.CREATE, true, SCOPES);
/**
* The permission for updating credentials in a {@link CredentialsStore}.
*
* @since 1.8
*/
public static final Permission UPDATE = new Permission(GROUP, "Update",
Messages._CredentialsProvider_UpdatePermissionDescription(), Permission.UPDATE, true, SCOPES);
/**
* The permission for viewing credentials in a {@link CredentialsStore}.
*
* @since 1.8
*/
public static final Permission VIEW = new Permission(GROUP, "View",
Messages._CredentialsProvider_ViewPermissionDescription(), Permission.READ, true, SCOPES);
/**
* The permission for removing credentials from a {@link CredentialsStore}.
*
* @since 1.8
*/
public static final Permission DELETE = new Permission(GROUP, "Delete",
Messages._CredentialsProvider_DeletePermissionDescription(), Permission.DELETE, true, SCOPES);
/**
* The permission for managing credential domains in a {@link CredentialsStore}.
*
* @since 1.8
*/
public static final Permission MANAGE_DOMAINS = new Permission(GROUP, "ManageDomains",
Messages._CredentialsProvider_ManageDomainsPermissionDescription(), Permission.CONFIGURE, true, SCOPES);
/**
* The system property name corresponding to {@link #FINGERPRINT_ENABLED}.
*/
private static final String FINGERPRINT_ENABLED_NAME = CredentialsProvider.class.getSimpleName() + ".fingerprintEnabled";
/**
* Control if the fingerprints must be used or not.
* By default they are activated and thus allow the tracking of credentials usage.
* In case of performance troubles in some weird situation, you can disable the behavior by setting it to {@code false}.
*/
@Restricted(NoExternalUse.class)
/* package-protected */ static /* not final */ boolean FINGERPRINT_ENABLED = Boolean.parseBoolean(System.getProperty(FINGERPRINT_ENABLED_NAME, "true"));
/**
* Default constructor.
*/
@SuppressWarnings("unchecked")
public CredentialsProvider() {
super(Descriptor.self());
}
/**
* Returns all the registered {@link com.cloudbees.plugins.credentials.Credentials} descriptors.
*
* @return all the registered {@link com.cloudbees.plugins.credentials.Credentials} descriptors.
*/
public static DescriptorExtensionList<Credentials, CredentialsDescriptor> allCredentialsDescriptors() {
return Jenkins.get().getDescriptorList(Credentials.class);
}
/**
* @deprecated use {@link #lookupCredentialsInItem(Class, Item, Authentication, List)}
* or {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication, List)}
*/
@Deprecated
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type) {
return lookupCredentials(type, (Item) null, ACL.SYSTEM);
}
/**
* @deprecated use {@link #lookupCredentialsInItem(Class, Item, Authentication, List)},
* {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication, List)}
*/
@Deprecated
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable org.acegisecurity.Authentication authentication) {
return lookupCredentials(type, Jenkins.get(), authentication);
}
/**
* @deprecated use {@link #lookupCredentialsInItem(Class, Item, Authentication, List)} instead.
*/
@Deprecated
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable Item item) {
return item == null
? lookupCredentials(type, Jenkins.get(), ACL.SYSTEM)
: lookupCredentials(type, item, ACL.SYSTEM);
}
/**
* @deprecated use {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication, List)} instead.
*/
@Deprecated
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup) {
return lookupCredentials(type, itemGroup, ACL.SYSTEM);
}
/**
* @deprecated use {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication)} instead.
*/
@Deprecated
@NonNull
@SuppressWarnings({"unchecked", "unused"}) // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable org.acegisecurity.Authentication authentication) {
return lookupCredentialsInItemGroup(type, itemGroup, authentication == null ? null : authentication.toSpring(), Collections.emptyList());
}
/**
* @deprecated use {@link #lookupCredentialsInItem(Class, Item, Authentication)} instead.
*/
@Deprecated
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable Item item,
@Nullable org.acegisecurity.Authentication authentication) {
return lookupCredentialsInItem(type, item, authentication == null ? null : authentication.toSpring(), Collections.emptyList());
}
/**
* @deprecated Use {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication)} or {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication, List)}.
*/
@Deprecated
@NonNull
@SuppressWarnings({"unchecked", "unused"}) // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable org.acegisecurity.Authentication authentication,
@Nullable DomainRequirement... domainRequirements) {
return lookupCredentialsInItemGroup(type, itemGroup, authentication == null ? null : authentication.toSpring(), Arrays.asList(domainRequirements == null ? new DomainRequirement[0] : domainRequirements));
}
/**
* Returns all credentials which are available to the specified {@link Authentication}
* for use by the {@link Item}s in the specified {@link ItemGroup}.
*
* @param type the type of credentials to get.
* @param itemGroup the item group.
* @param authentication the authentication.
* @param <C> the credentials type.
* @return the list of credentials.
* @since TODO
*/
@NonNull
@SuppressWarnings({"unchecked", "unused"}) // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentialsInItemGroup(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable Authentication authentication) {
return lookupCredentialsInItemGroup(type, itemGroup, authentication, List.of());
}
/**
* @deprecated Use {@link #lookupCredentialsInItemGroup(Class, ItemGroup, Authentication, List)} instead.
*/
@NonNull
@SuppressWarnings({"unchecked", "unused"}) // API entry point for consumers
@Deprecated
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable org.acegisecurity.Authentication authentication,
@Nullable List<DomainRequirement> domainRequirements) {
return lookupCredentialsInItemGroup(type, itemGroup, authentication == null ? null : authentication.toSpring(), domainRequirements);
}
/**
* Returns all credentials which are available to the specified {@link Authentication}
* for use by the {@link Item}s in the specified {@link ItemGroup}.
*
* @param type the type of credentials to get.
* @param itemGroup the item group.
* @param authentication the authentication.
* @param domainRequirements the credential domains to match.
* @param <C> the credentials type.
* @return the list of credentials.
* @since TODO
*/
@NonNull
@SuppressWarnings({"unchecked", "unused"}) // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentialsInItemGroup(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable Authentication authentication,
@Nullable List<DomainRequirement> domainRequirements) {
Objects.requireNonNull(type);
Jenkins jenkins = Jenkins.get();
itemGroup = itemGroup == null ? jenkins : itemGroup;
authentication = authentication == null ? ACL.SYSTEM2 : authentication;
domainRequirements = domainRequirements
== null ? Collections.emptyList() : domainRequirements;
CredentialsResolver<Credentials, C> resolver = CredentialsResolver.getResolver(type);
if (resolver != null) {
LOGGER.log(Level.FINE, "Resolving legacy credentials of type {0} with resolver {1}",
new Object[]{type, resolver});
final List<Credentials> originals =
lookupCredentialsInItemGroup(resolver.getFromClass(), itemGroup, authentication, domainRequirements);
LOGGER.log(Level.FINE, "Original credentials for resolving: {0}", originals);
return resolver.resolve(originals);
}
List<C> result = new ArrayList<>();
Set<String> ids = new HashSet<>();
for (CredentialsProvider provider : all()) {
if (provider.isEnabled(itemGroup) && provider.isApplicable(type)) {
try {
for (C c : provider.getCredentialsInItemGroup(type, itemGroup, authentication, domainRequirements)) {
if (!(c instanceof IdCredentials) || ids.add(((IdCredentials) c).getId())) {
// if IdCredentials, only add if we haven't added already
// if not IdCredentials, always add
result.add(c);
}
}
} catch (NoClassDefFoundError e) {
LOGGER.log(Level.FINE, "Could not retrieve provider credentials from " + provider
+ " likely due to missing optional dependency", e);
}
}
}
return result;
}
/**
* @deprecated Use {@link #listCredentialsInItemGroup(Class, ItemGroup, Authentication, List, CredentialsMatcher)} instead.
*/
@Deprecated
public static <C extends IdCredentials> ListBoxModel listCredentials(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable org.acegisecurity.Authentication authentication,
@Nullable List<DomainRequirement>
domainRequirements,
@Nullable CredentialsMatcher matcher) {
return listCredentialsInItemGroup(type, itemGroup, authentication == null ? null : authentication.toSpring(), domainRequirements, matcher);
}
/**
* Returns a {@link ListBoxModel} of all credentials which are available to the specified {@link Authentication}
* for use by the {@link Item}s in the specified {@link ItemGroup}.
*
* @param type the type of credentials to get.
* @param authentication the authentication.
* @param itemGroup the item group.
* @param domainRequirements the credential domains to match.
* @param matcher the additional filtering to apply to the credentials
* @param <C> the credentials type.
* @return the {@link ListBoxModel} of {@link IdCredentials#getId()} with the corresponding display names as
* provided by {@link CredentialsNameProvider}.
* @since TODO
*/
public static <C extends IdCredentials> ListBoxModel listCredentialsInItemGroup(@NonNull Class<C> type,
@Nullable ItemGroup itemGroup,
@Nullable Authentication authentication,
@Nullable List<DomainRequirement>
domainRequirements,
@Nullable CredentialsMatcher matcher) {
Objects.requireNonNull(type);
Jenkins jenkins = Jenkins.get();
itemGroup = itemGroup == null ? jenkins : itemGroup;
authentication = authentication == null ? ACL.SYSTEM2 : authentication;
domainRequirements =
domainRequirements == null ? Collections.emptyList() : domainRequirements;
matcher = matcher == null ? CredentialsMatchers.always() : matcher;
CredentialsResolver<Credentials, C> resolver = CredentialsResolver.getResolver(type);
if (resolver != null && IdCredentials.class.isAssignableFrom(resolver.getFromClass())) {
LOGGER.log(Level.FINE, "Listing legacy credentials of type {0} identified by resolver {1}",
new Object[]{type, resolver});
return listCredentialsInItemGroup((Class) resolver.getFromClass(), itemGroup, authentication, domainRequirements,
matcher);
}
ListBoxModel result = new ListBoxModel();
Set<String> ids = new HashSet<>();
for (CredentialsProvider provider : all()) {
if (provider.isEnabled(itemGroup) && provider.isApplicable(type)) {
try {
for (ListBoxModel.Option option : provider.getCredentialIdsInItemGroup(
type, itemGroup, authentication, domainRequirements, matcher)
) {
if (ids.add(option.value)) {
result.add(option);
}
}
} catch (NoClassDefFoundError e) {
LOGGER.log(Level.FINE, "Could not retrieve provider credentials from " + provider
+ " likely due to missing optional dependency", e);
}
}
}
result.sort(new ListBoxModelOptionComparator());
return result;
}
/**
* @deprecated use {@link #lookupCredentialsInItem(Class, Item, Authentication)} or {@link #lookupCredentialsInItem(Class, Item, Authentication, List)}.
*/
@Deprecated
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable Item item,
@Nullable org.acegisecurity.Authentication authentication,
DomainRequirement... domainRequirements) {
return lookupCredentialsInItem(type, item, authentication == null ? null : authentication.toSpring(), Arrays.asList(domainRequirements));
}
/**
* Returns all credentials which are available to the specified {@link Authentication}
* for use by the specified {@link Item}.
*
* @param type the type of credentials to get.
* @param authentication the authentication.
* @param item the item.
* @param <C> the credentials type.
* @return the list of credentials.
* @since TODO
*/
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentialsInItem(@NonNull Class<C> type,
@Nullable Item item,
@Nullable Authentication authentication) {
return lookupCredentialsInItem(type, item, authentication, List.of());
}
/**
* @deprecated use {@link #lookupCredentialsInItem(Class, Item, Authentication, List)}
*/
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
@Deprecated
public static <C extends Credentials> List<C> lookupCredentials(@NonNull Class<C> type,
@Nullable Item item,
@Nullable org.acegisecurity.Authentication authentication,
@Nullable List<DomainRequirement>
domainRequirements) {
return lookupCredentialsInItem(type, item, authentication == null ? null : authentication.toSpring(), domainRequirements);
}
/**
* Returns all credentials which are available to the specified {@link Authentication}
* for use by the specified {@link Item}.
*
* @param type the type of credentials to get.
* @param authentication the authentication.
* @param item the item.
* @param domainRequirements the credential domains to match.
* @param <C> the credentials type.
* @return the list of credentials.
* @since TODO
*/
@NonNull
@SuppressWarnings("unused") // API entry point for consumers
public static <C extends Credentials> List<C> lookupCredentialsInItem(@NonNull Class<C> type,
@Nullable Item item,
@Nullable Authentication authentication,
@Nullable List<DomainRequirement>
domainRequirements) {
Objects.requireNonNull(type);
if (item == null) {
return lookupCredentialsInItemGroup(type, Jenkins.get(), authentication, domainRequirements);
}
if (item instanceof ItemGroup) {
return lookupCredentialsInItemGroup(type, (ItemGroup)item, authentication, domainRequirements);
}
authentication = authentication == null ? ACL.SYSTEM2 : authentication;
domainRequirements = domainRequirements
== null ? Collections.emptyList() : domainRequirements;
CredentialsResolver<Credentials, C> resolver = CredentialsResolver.getResolver(type);
if (resolver != null) {
LOGGER.log(Level.FINE, "Resolving legacy credentials of type {0} with resolver {1}",
new Object[]{type, resolver});
final List<Credentials> originals =
lookupCredentialsInItem(resolver.getFromClass(), item, authentication, domainRequirements);
LOGGER.log(Level.FINE, "Original credentials for resolving: {0}", originals);
return resolver.resolve(originals);
}
List<C> result = new ArrayList<>();
Set<String> ids = new HashSet<>();
for (CredentialsProvider provider : all()) {
if (provider.isEnabled(item) && provider.isApplicable(type)) {
try {
for (C c: provider.getCredentialsInItem(type, item, authentication, domainRequirements)) {
if (!(c instanceof IdCredentials) || ids.add(((IdCredentials) c).getId())) {
// if IdCredentials, only add if we haven't added already
// if not IdCredentials, always add
result.add(c);
}
}
} catch (NoClassDefFoundError e) {
LOGGER.log(Level.FINE, "Could not retrieve provider credentials from " + provider
+ " likely due to missing optional dependency", e);
}
}
}
return result;
}
/**
* @deprecated Use {@link #listCredentialsInItem(Class, Item, Authentication, List, CredentialsMatcher)} instead.
*/
@NonNull
@Deprecated
public static <C extends IdCredentials> ListBoxModel listCredentials(@NonNull Class<C> type,
@Nullable Item item,
@Nullable org.acegisecurity.Authentication authentication,
@Nullable List<DomainRequirement>
domainRequirements,
@Nullable CredentialsMatcher matcher) {
return listCredentialsInItem(type, item, authentication == null ? null : authentication.toSpring(), domainRequirements, matcher);
}
/**
* Returns a {@link ListBoxModel} of all credentials which are available to the specified {@link Authentication}
* for use by the specified {@link Item}.
*
* @param type the type of credentials to get.
* @param authentication the authentication.
* @param item the item.
* @param domainRequirements the credential domains to match.
* @param matcher the additional filtering to apply to the credentials
* @param <C> the credentials type.
* @return the {@link ListBoxModel} of {@link IdCredentials#getId()} with the corresponding display names as
* provided by {@link CredentialsNameProvider}.
* @since TODO
*/
@NonNull
public static <C extends IdCredentials> ListBoxModel listCredentialsInItem(@NonNull Class<C> type,
@Nullable Item item,
@Nullable Authentication authentication,
@Nullable List<DomainRequirement>
domainRequirements,
@Nullable CredentialsMatcher matcher) {
Objects.requireNonNull(type);
if (item == null) {
return listCredentialsInItemGroup(type, Jenkins.get(), authentication, domainRequirements, matcher);
}
if (item instanceof ItemGroup) {
return listCredentialsInItemGroup(type, (ItemGroup) item, authentication, domainRequirements, matcher);
}
authentication = authentication == null ? ACL.SYSTEM2 : authentication;
domainRequirements = domainRequirements
== null ? Collections.emptyList() : domainRequirements;
CredentialsResolver<Credentials, C> resolver = CredentialsResolver.getResolver(type);
if (resolver != null && IdCredentials.class.isAssignableFrom(resolver.getFromClass())) {
LOGGER.log(Level.FINE, "Listing legacy credentials of type {0} identified by resolver {1}",
new Object[]{type, resolver});
return listCredentialsInItem((Class) resolver.getFromClass(), item, authentication,
domainRequirements, matcher);
}
ListBoxModel result = new ListBoxModel();
Set<String> ids = new HashSet<>();
for (CredentialsProvider provider : all()) {
if (provider.isEnabled(item) && provider.isApplicable(type)) {
try {
for (ListBoxModel.Option option : provider.getCredentialIdsInItem(
type, item, authentication, domainRequirements, matcher == null ? CredentialsMatchers.always() : matcher)
) {
if (ids.add(option.value)) {
result.add(option);
}
}
} catch (NoClassDefFoundError e) {
LOGGER.log(Level.FINE, "Could not retrieve provider credentials from " + provider
+ " likely due to missing optional dependency", e);
}
}
}
result.sort(new ListBoxModelOptionComparator());
return result;
}
/**
* Returns the scopes allowed for credentials stored within the specified object or {@code null} if the
* object is not relevant for scopes and the object's container should be considered instead.
*
* @param object the object.
* @return the set of scopes that are relevant for the object or {@code null} if the object is not a credentials
* container.
*/
@CheckForNull
public static Set<CredentialsScope> lookupScopes(ModelObject object) {
object = CredentialsDescriptor.unwrapContext(object);
Set<CredentialsScope> result = null;
for (CredentialsProvider provider : all()) {
if (provider.isEnabled(object)) {
try {
Set<CredentialsScope> scopes = provider.getScopes(object);
if (scopes != null) {
// if multiple providers for the same object, then combine scopes
if (result == null) {
result = new LinkedHashSet<>();
}
result.addAll(scopes);
}
} catch (NoClassDefFoundError e) {
// ignore optional dependency
}
}
}
return result;
}
/**
* Tests if the supplied context has any credentials stores associated with it.
*
* @param context the context object.
* @return {@code true} if and only if the supplied context has at least one {@link CredentialsStore} associated
* with it.
* @since 2.1.5
*/
public static boolean hasStores(final ModelObject context) {
for (CredentialsProvider p : all()) {
if (p.isEnabled(context) && p.getStore(context) != null) {
return true;
}
}
return false;
}
/**
* Returns a lazy {@link Iterable} of all the {@link CredentialsStore} instances contributing credentials to the
* supplied object.
*
* @param context the {@link Item} or {@link ItemGroup} or {@link User} to get the {@link CredentialsStore}s of.
* @return a lazy {@link Iterable} of all {@link CredentialsStore} instances.
* @since 1.8
*/
public static Iterable<CredentialsStore> lookupStores(final ModelObject context) {
final ExtensionList<CredentialsProvider> providers = all();
return () -> new Iterator<CredentialsStore>() {
private ModelObject current = context;
private Iterator<CredentialsProvider> iterator = providers.iterator();
private CredentialsStore next;
public boolean hasNext() {
if (next != null) {
return true;
}
while (current != null) {
while (iterator.hasNext()) {
CredentialsProvider p = iterator.next();
if (!p.isEnabled(context)) {
continue;
}
next = p.getStore(current);
if (next != null) {
return true;
}
}
// now walk up the model object tree
// TODO make this an extension point perhaps ContextResolver could help
if (current instanceof Item) {
current = ((Item) current).getParent();
iterator = providers.iterator();
} else if (current instanceof User) {
Jenkins jenkins = Jenkins.get();
Authentication a;
if (jenkins.hasPermission(USE_ITEM) && current == User.current()) {
// this is the fast path for the 99% of cases
a = Jenkins.getAuthentication2();
} else {
try {
a = ((User) current).impersonate2();
} catch (UsernameNotFoundException e) {
a = Jenkins.ANONYMOUS2;
}
}
if (current == User.current() && jenkins.getACL().hasPermission2(a, USE_ITEM)) {
current = jenkins;
iterator = providers.iterator();
} else {
current = null;
}
} else if (current instanceof Jenkins) {
// escape
current = null;
} else if (current instanceof ComputerSet) {
current = Jenkins.get();
iterator = providers.iterator();
} else if (current instanceof Computer) {
current = Jenkins.get();
iterator = providers.iterator();
} else if (current instanceof Node) {
current = Jenkins.get();
iterator = providers.iterator();
} else {
// fall back to Jenkins as the ultimate parent of everything else
current = Jenkins.get();
iterator = providers.iterator();
}
}
return false;
}
public CredentialsStore next() {
if (!hasNext()) {
throw new NoSuchElementException();
}
try {
return next;
} finally {
next = null;
}
}
};
}
/**
* Make a best effort to ensure that the supplied credential is a snapshot credential (i.e. self-contained and
* does not reference any external stores). <b>WARNING:</b> May produce unusual results if presented an exotic
* credential that implements multiple distinct credential types at the same time, e.g. a credential that is
* simultaneously a TLS certificate and a SSH key pair and a GPG key pair all at the same time... unless the
* author of that credential type also provides a {@link CredentialsSnapshotTaker} that can handle such a
* triple play.
*
* @param credential the credential.
* @param <C> the type of credential.
* @return the credential or a snapshot of the credential.
* @since 1.14
*/
@SuppressWarnings("unchecked")
public static <C extends Credentials> C snapshot(C credential) {
return (C) snapshot(Credentials.class, credential);
}
/**
* Make a best effort to ensure that the supplied credential is a snapshot credential (i.e. self-contained and
* does not reference any external stores)
*
* @param clazz the type of credential that we are trying to snapshot (specified so that if there is more than
* one type of snapshot able credential interface implemented by the credentials,
* then they can be separated out.
* @param credential the credential.
* @param <C> the type of credential.
* @return the credential or a snapshot of the credential.
* @since 1.14
*/
@SuppressWarnings("unchecked")
public static <C extends Credentials> C snapshot(Class<C> clazz, C credential) {
Class bestType = null;
CredentialsSnapshotTaker bestTaker = null;
for (CredentialsSnapshotTaker taker : ExtensionList.lookup(CredentialsSnapshotTaker.class)) {
if (clazz.isAssignableFrom(taker.type()) && taker.type().isInstance(credential)) {
if (bestTaker == null || bestType.isAssignableFrom(taker.type())) {
bestTaker = taker;
bestType = taker.type();
}
}
}
if (bestTaker == null) {
return credential;
}
return clazz.cast(bestTaker.snapshot(credential));
}
/**
* Helper method to get the default authentication to use for an {@link Item}.
*/
@NonNull
/*package*/ static Authentication getDefaultAuthenticationOf2(Item item) {
if (item instanceof Queue.Task) {
return Tasks.getAuthenticationOf2((Queue.Task) item);
} else {
return ACL.SYSTEM2;
}
}
/**
* A common requirement for plugins is to resolve a specific credential by id in the context of a specific run.
* Given that the credential itself could be resulting from a build parameter expression and the complexities of
* determining the scope of items from which the credential should be resolved in a chain of builds, this method
* provides the correct answer.
*
* @param id either the id of the credential to find or a parameter expression for the id.
* @param type the type of credential to find.
* @param run the {@link Run} defining the context within which to find the credential.
* @param <C> the credentials type.
* @return the credential or {@code null} if either the credential cannot be found or the user triggering the run
* is not permitted to use the credential in the context of the run.
* @since TODO
*/
@CheckForNull
public static <C extends IdCredentials> C findCredentialById(@NonNull String id, @NonNull Class<C> type,
@NonNull Run<?, ?> run) {
return findCredentialById(id, type, run, List.of());
}
/**
* @deprecated Use {@link #findCredentialById(String, Class, Run, List)} instead.
*/
public static <C extends IdCredentials> C findCredentialById(@NonNull String id, @NonNull Class<C> type,
@NonNull Run<?, ?> run,
DomainRequirement... domainRequirements) {
return findCredentialById(id, type, run, Arrays.asList(domainRequirements));
}
/**
* A common requirement for plugins is to resolve a specific credential by id in the context of a specific run.
* Given that the credential itself could be resulting from a build parameter expression and the complexities of
* determining the scope of items from which the credential should be resolved in a chain of builds, this method
* provides the correct answer.
*
* @param id either the id of the credential to find or a parameter expression for the id.
* @param type the type of credential to find.
* @param run the {@link Run} defining the context within which to find the credential.
* @param domainRequirements the domain requirements of the credential.
* @param <C> the credentials type.
* @return the credential or {@code null} if either the credential cannot be found or the user triggering the run
* is not permitted to use the credential in the context of the run.
* @since 1.16
*/
@CheckForNull
public static <C extends IdCredentials> C findCredentialById(@NonNull String id, @NonNull Class<C> type,
@NonNull Run<?, ?> run,
@Nullable List<DomainRequirement> domainRequirements) {
Objects.requireNonNull(id);
Objects.requireNonNull(type);
Objects.requireNonNull(run);
// first we need to find out if this id is pre-selected or a parameter
id = id.trim();
boolean isParameter = false;
boolean isDefaultValue = false;
String inputUserId = null;
final String parameterName;
if (id.startsWith("${") && id.endsWith("}")) {
// denotes explicitly that this is a parameterized credential
parameterName = id.substring(2, id.length() - 1);
} else {
// otherwise, we can check to see if there is a matching credential parameter name that shadows an
// existing global credential id
parameterName = id;
}
final CredentialsParameterBinder binder = CredentialsParameterBinder.getOrCreate(run);
final CredentialsParameterBinding binding = binder.forParameterName(parameterName);
if (binding != null) {
isParameter = true;
inputUserId = binding.getUserId();
isDefaultValue = binding.isDefaultValue();
id = Util.fixNull(binding.getCredentialsId());
}
// non parameters or default parameter values can only come from the job's context
if (!isParameter || isDefaultValue) {
// we use the default authentication of the job as those are the only ones that can be configured
// if a different strategy is in play it doesn't make sense to consider the run-time authentication
// as you would have no way to configure it
Authentication runAuth = CredentialsProvider.getDefaultAuthenticationOf2(run.getParent());
// we want the credentials available to the user the build is running as
List<C> candidates = new ArrayList<>(
CredentialsProvider.lookupCredentialsInItem(type, run.getParent(), runAuth, domainRequirements)
);
// if that user can use the item's credentials, add those in too
if (runAuth != ACL.SYSTEM2 && run.hasPermission2(runAuth, CredentialsProvider.USE_ITEM)) {
candidates.addAll(
CredentialsProvider.lookupCredentialsInItem(type, run.getParent(), ACL.SYSTEM2, domainRequirements)
);
}
// TODO should this be calling track?
return contextualize(type, CredentialsMatchers.firstOrNull(candidates, CredentialsMatchers.withId(id)), run);
}
// this is a parameter and not the default value, we need to determine who triggered the build
final Map.Entry<User, Run<?, ?>> triggeredBy = triggeredBy(run);
final Authentication a = triggeredBy == null ? Jenkins.ANONYMOUS2 : triggeredBy.getKey().impersonate2();
List<C> candidates = new ArrayList<>();
if (triggeredBy != null && run == triggeredBy.getValue() && run.hasPermission2(a, CredentialsProvider.USE_OWN)) {
// the user triggered this job directly and they are allowed to supply their own credentials, so
// add those into the list. We do not want to follow the chain for the user's authentication
// though, as there is no way to limit how far the passed-through parameters can be used
candidates.addAll(CredentialsProvider.lookupCredentialsInItem(type, run.getParent(), a, domainRequirements));
}
if (inputUserId != null) {
final User inputUser = User.getById(inputUserId, false);
if (inputUser != null) {
final Authentication inputAuth = inputUser.impersonate2();
if (run.hasPermission2(inputAuth, CredentialsProvider.USE_OWN)) {
candidates.addAll(CredentialsProvider.lookupCredentialsInItem(type, run.getParent(), inputAuth, domainRequirements));
}
}
}
if (run.hasPermission2(a, CredentialsProvider.USE_ITEM)) {
// the triggering user is allowed to use the item's credentials, so add those into the list
// we use the default authentication of the job as those are the only ones that can be configured
// if a different strategy is in play it doesn't make sense to consider the run-time authentication
// as you would have no way to configure it
Authentication runAuth = CredentialsProvider.getDefaultAuthenticationOf2(run.getParent());
// we want the credentials available to the user the build is running as
candidates.addAll(
CredentialsProvider.lookupCredentialsInItem(type, run.getParent(), runAuth, domainRequirements)
);
// if that user can use the item's credentials, add those in too
if (runAuth != ACL.SYSTEM2 && run.hasPermission2(runAuth, CredentialsProvider.USE_ITEM)) {
candidates.addAll(
CredentialsProvider.lookupCredentialsInItem(type, run.getParent(), ACL.SYSTEM2, domainRequirements)
);
}
}
C result = CredentialsMatchers.firstOrNull(candidates, CredentialsMatchers.withId(id));
// if the run has not completed yet then we can safely assume that the credential is being used for this run
// so we will track it's usage. We use isLogUpdated() as it could be used during post production
if (run.isLogUpdated()) {
track(run, result);
}
return contextualize(type, result, run);
}
@CheckForNull
private static <C extends Credentials> C contextualize(@NonNull Class<C> type, @CheckForNull C credentials, @NonNull Run<?, ?> run) {
if (credentials != null) {
Credentials contextualized = credentials.forRun(run);
if (type.isInstance(contextualized)) {
return type.cast(contextualized);
} else {
LOGGER.warning(() -> "Ignoring " + contextualized.getClass().getName() + " return value of " + credentials.getClass().getName() + ".forRun since it is not assignable to " + type.getName());
}
}
return credentials;
}
/**
* Identifies the {@link User} and {@link Run} that triggered the supplied {@link Run}.
*