forked from jenkinsci/credentials-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCredentialsSelectHelper.java
More file actions
948 lines (880 loc) · 34.5 KB
/
CredentialsSelectHelper.java
File metadata and controls
948 lines (880 loc) · 34.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
/*
* The MIT License
*
* Copyright (c) 2013-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 edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.ExtensionList;
import hudson.ExtensionPoint;
import hudson.Util;
import hudson.cli.declarative.CLIResolver;
import hudson.model.ComputerSet;
import hudson.model.Describable;
import hudson.model.Descriptor;
import hudson.model.Item;
import hudson.model.ModelObject;
import hudson.model.User;
import hudson.security.AccessControlled;
import hudson.security.Permission;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeMap;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;
import jakarta.servlet.ServletException;
import jenkins.model.Jenkins;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.jenkins.ui.icon.IconSpec;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.NoExternalUse;
import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.Localizable;
import org.kohsuke.stapler.StaplerRequest2;
import org.kohsuke.stapler.StaplerResponse2;
import org.kohsuke.stapler.interceptor.RequirePOST;
/**
* A descriptor used to assist the c:select tag with allowing in-place addition of credentials.
*
* @author Stephen Connolly
*/
@Extension
public class CredentialsSelectHelper extends Descriptor<CredentialsSelectHelper> implements
Describable<CredentialsSelectHelper> {
/**
* Expose the {@link CredentialsProvider#CREATE} permission for Jelly.
*/
public static final Permission CREATE = CredentialsProvider.CREATE;
private static final Logger LOGGER = Logger.getLogger(CredentialsSelectHelper.class.getName());
/**
* Constructor.
*
* @see CredentialsSelectHelper
* @see Descriptor<CredentialsSelectHelper>#Descriptor()
*/
public CredentialsSelectHelper() {
super(CredentialsSelectHelper.class);
}
/**
* {@inheritDoc}
*/
public CredentialsSelectHelper getDescriptor() {
return this;
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public String getDisplayName() {
return Messages.CredentialsSelectHelper_DisplayName();
}
/**
* Fixes up the context in case we are called from a page where the context is not a ModelObject.
*
* @param context the initial guess of the context.
* @return the resolved context.
* @since 2.0.7
*/
@CheckForNull
@Restricted(NoExternalUse.class)
public ModelObject resolveContext(Object context) {
return context instanceof ModelObject mo ? mo : CredentialsDescriptor.findContextInPath(ModelObject.class);
}
/**
* @return modifiable store actions for the context provided.
*/
@Restricted(NoExternalUse.class)
public Map<String, List<CredentialsStoreAction.DomainWrapper>> getModifiableStoreActions(ModelObject context) {
return StreamSupport.stream(CredentialsProvider.lookupStores(context).spliterator(), false)
.filter(s -> s.hasPermission(CredentialsProvider.CREATE))
.map(CredentialsStore::getStoreAction)
.filter(Objects::nonNull)
.collect(Collectors.toMap(
CredentialsStoreAction::getFullDisplayName,
store -> new ArrayList<>(store.getDomains().values()),
(left, right) -> {
left.addAll(right);
return left;
},
LinkedHashMap::new
));
}
/**
* Returns the {@link StoreItem} instances for the current Stapler request.
*
* @param context the context in which to retrieve the store items.
* @param includeUser {@code true} to also include any User scoped stores.
* @return the {@link StoreItem} instances for the current Stapler request.
* @since 2.0.5
*/
@Restricted(NoExternalUse.class)
public List<StoreItem> getStoreItems(ModelObject context, boolean includeUser) {
Set<String> urls = new HashSet<>();
List<StoreItem> result = new ArrayList<>();
if (context == null) {
context = CredentialsDescriptor.findContextInPath(ModelObject.class);
}
if (context != null) {
for (CredentialsStore store : CredentialsProvider.lookupStores(context)) {
StoreItem item = new StoreItem(store);
String url = item.getUrl();
if (item.getUrl() != null && !urls.contains(url)) {
result.add(item);
urls.add(url);
}
}
}
if (includeUser) {
boolean hasPermission = false;
ModelObject current = context;
while (current != null) {
if (current instanceof AccessControlled) {
hasPermission = ((AccessControlled) current).hasPermission(CredentialsProvider.USE_OWN);
break;
} else if (current instanceof ComputerSet) {
current = Jenkins.get();
} else {
// fall back to Jenkins as the ultimate parent of everything else
current = Jenkins.get();
}
}
if (hasPermission) {
for (CredentialsStore store : CredentialsProvider.lookupStores(User.current())) {
StoreItem item = new StoreItem(store);
String url = item.getUrl();
if (item.getUrl() != null && !urls.contains(url)) {
result.add(item);
urls.add(url);
}
}
}
}
return result;
}
/**
* Checks if the current user has permission to create a credential.
*
* @param context the context.
* @param includeUser whether they can use their own credentials store.
* @return {@code true} if they can create a permission.
* @since FIXME
*/
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // used via jelly
public boolean hasCreatePermission(ModelObject context, boolean includeUser) {
if (includeUser) {
User current = User.current();
if (current != null && current.hasPermission(CREATE)) {
return true;
}
}
if (context == null) {
context = CredentialsDescriptor.findContextInPath(ModelObject.class);
}
for (CredentialsStore store : CredentialsProvider.lookupStores(context)) {
if (store.hasPermission(CREATE)) {
return true;
}
}
return false;
}
/**
* Stapler binding for the resolver URL segment.
*
* @param className the class name of the resolver.
* @return the wrapped resolver.
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public WrappedContextResolver getResolver(String className) {
return ExtensionList.lookup(ContextResolver.class)
.stream()
.filter(r -> r.getClass().getName().equals(className))
.findFirst()
.map(WrappedContextResolver::new)
.orElse(null);
}
/**
* Resolves a {@link CredentialsStore} instance for CLI commands.
*
* @param storeId the store identifier.
* @return the {@link CredentialsStore} instance.
* @throws CmdLineException if the store cannot be resolved.
* @since 2.1.1
*/
@CLIResolver
public static CredentialsStore resolveForCLI(
@Argument(required = true, metaVar = "STORE", usage = "Store ID") String storeId) throws
CmdLineException {
int index1 = storeId.indexOf("::");
int index2 = index1 == -1 ? -1 : storeId.indexOf("::", index1 + 2);
if (index1 == -1 || index1 == 0 || index2 == -1 || index2 < (index1 + 2) || index2 == storeId.length() - 2) {
throw new CmdLineException(null, new Localizable() {
@Override
public String formatWithLocale(Locale locale, Object... objects) {
return Messages._CredentialsSelectHelper_CLIMalformedStoreId(objects[0]).toString(locale);
}
@Override
public String format(Object... objects) {
return Messages._CredentialsSelectHelper_CLIMalformedStoreId(objects[0]).toString();
}
}, storeId);
}
String providerName = storeId.substring(0, index1);
String resolverName = storeId.substring(index1 + 2, index2);
String token = storeId.substring(index2 + 2);
CredentialsProvider provider = getProvidersByName().get(providerName);
if (provider == null || provider == CredentialsProvider.NONE) {
throw new CmdLineException(null, new Localizable() {
@Override
public String formatWithLocale(Locale locale, Object... objects) {
return Messages._CredentialsSelectHelper_CLINoSuchProvider(objects[0]).toString(locale);
}
@Override
public String format(Object... objects) {
return Messages._CredentialsSelectHelper_CLINoSuchProvider(objects[0]).toString();
}
}, storeId);
}
ContextResolver resolver = getResolversByName().get(resolverName);
if (resolver == null || resolver == ContextResolver.NONE) {
throw new CmdLineException(null, new Localizable() {
@Override
public String formatWithLocale(Locale locale, Object... objects) {
return Messages._CredentialsSelectHelper_CLINoSuchResolver(objects[0]).toString(locale);
}
@Override
public String format(Object... objects) {
return Messages._CredentialsSelectHelper_CLINoSuchResolver(objects[0]).toString();
}
}, storeId);
}
ModelObject context = resolver.getContext(token);
if (context == null) {
throw new CmdLineException(null, new Localizable() {
@Override
public String formatWithLocale(Locale locale, Object... objects) {
return Messages._CredentialsSelectHelper_CLINoSuchContext(objects[0]).toString(locale);
}
@Override
public String format(Object... objects) {
return Messages._CredentialsSelectHelper_CLINoSuchContext(objects[0]).toString();
}
}, storeId);
}
CredentialsStore store = provider.getStore(context);
if (store == null) {
throw new CmdLineException(null, new Localizable() {
@Override
public String formatWithLocale(Locale locale, Object... objects) {
return Messages._CredentialsSelectHelper_CLINoStore().toString(locale);
}
@Override
public String format(Object... objects) {
return Messages._CredentialsSelectHelper_CLINoStore().toString();
}
}, storeId);
}
return store;
}
/**
* Returns a map of the {@link ContextResolver} instances keyed by their name. A resolver may have more than one
* entry if there are inferred unique short nicknames.
*
* @return a map of the {@link ContextResolver} instances keyed by their name
* @since 2.1.1
*/
public static Map<String, ContextResolver> getResolversByName() {
Map<String, ContextResolver> resolverByName = new TreeMap<>();
for (ContextResolver r : ExtensionList.lookup(ContextResolver.class)) {
resolverByName.put(r.getClass().getName(), r);
String shortName = r.getClass().getSimpleName();
resolverByName.put(shortName, resolverByName.containsKey(shortName) ? ContextResolver.NONE : r);
shortName = shortName.toLowerCase(Locale.ENGLISH).replaceAll("(context|resolver|impl)*", "");
if (StringUtils.isNotBlank(shortName)) {
resolverByName.put(shortName, resolverByName.containsKey(shortName) ? ContextResolver.NONE : r);
}
}
resolverByName.values().removeIf(r -> r == ContextResolver.NONE);
return resolverByName;
}
/**
* Returns a map of the {@link CredentialsProvider} instances keyed by their name. A provider may have more than one
* entry if there are inferred unique short nicknames.
*
* @return a map of the {@link CredentialsProvider} instances keyed by their name
* @since 2.1.1
*/
public static Map<String, CredentialsProvider> getProvidersByName() {
Map<String, CredentialsProvider> providerByName = new TreeMap<>();
for (CredentialsProvider r : ExtensionList.lookup(CredentialsProvider.class)) {
providerByName.put(r.getClass().getName(), r);
Class<?> clazz = r.getClass();
while (clazz != null) {
String shortName = clazz.getSimpleName();
clazz = clazz.getEnclosingClass();
String simpleName =
shortName.toLowerCase(Locale.ENGLISH).replaceAll("(credentials|provider|impl)*", "");
if (StringUtils.isBlank(simpleName)) continue;
providerByName.put(shortName, providerByName.containsKey(shortName) ? CredentialsProvider.NONE : r);
providerByName.put(simpleName, providerByName.containsKey(simpleName) ? CredentialsProvider.NONE : r);
}
}
providerByName.values().removeIf(p -> p == CredentialsProvider.NONE);
return providerByName;
}
/**
* Value class to hold the details of a {@link CredentialsStore}.
*
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public static final class StoreItem implements IconSpec, ModelObject {
/**
* The store.
*/
private final CredentialsStore store;
/**
* The URL we will expose the store at.
*/
private final String url;
/**
* Constructor.
*
* @param store the store.
*/
public StoreItem(CredentialsStore store) {
this.store = store;
String provider = store.getProvider().getClass().getName();
String resolver = null;
String token = null;
ModelObject storeContext = store.getContext();
// we only support the cases where the
for (ContextResolver r : ExtensionList.lookup(ContextResolver.class)) {
String t = r.getToken(storeContext);
if (t != null) {
resolver = r.getClass().getName();
token = t;
break;
}
}
this.url = token == null
? null
: String.format(
"descriptor/%s/resolver/%s/provider/%s/context/%s",
CredentialsSelectHelper.class.getName(),
Util.rawEncode(resolver),
Util.rawEncode(provider),
Util.rawEncode(token)
);
}
/**
* {@inheritDoc}
*/
@Override
public String getIconClassName() {
return store.getProvider().getIconClassName();
}
/**
* Exposes if this store is enabled for the current user.
*
* @return {@code true} if the current user can add credentials to this store.
*/
public boolean isEnabled() {
return url != null && store.hasPermission(CREATE) && !store.getCredentialsDescriptors()
.isEmpty();
}
/**
* {@inheritDoc}
*/
@Override
public String getDisplayName() {
return store.getContextDisplayName();
}
/**
* Exposes the description of this store (i.e. the {@link CredentialsProvider#getDisplayName()}.
*
* @return the description of this store (i.e. the {@link CredentialsProvider#getDisplayName()}.
*/
public String getDescription() {
return store.getProvider().getDisplayName();
}
/**
* Exposes the URL of this store's {@link WrappedCredentialsStore}.
*
* @return the URL of this store's {@link WrappedCredentialsStore}
*/
public String getUrl() {
return url;
}
}
/**
* Stapler binding for {@link ContextResolver}.
*
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public static final class WrappedContextResolver {
/**
* Our {@link ContextResolver}
*/
@NonNull
private final ContextResolver resolver;
/**
* Our constructor.
*
* @param resolver the {@link ContextResolver}
*/
public WrappedContextResolver(@NonNull ContextResolver resolver) {
this.resolver = resolver;
}
/**
* Stapler web binding for the {@link CredentialsProvider}.
*
* @param className the class name of the {@link CredentialsProvider}.
* @return the {@link WrappedContextResolverCredentialsProvider} or {@code null}
*/
@CheckForNull
public WrappedContextResolverCredentialsProvider getProvider(String className) {
for (CredentialsProvider p : CredentialsProvider.enabled()) {
if (p.getClass().getName().equals(className)) {
return new WrappedContextResolverCredentialsProvider(resolver, p);
}
}
return null;
}
}
/**
* Stapler binding for a {@link ContextResolver} and {@link CredentialsProvider}.
*
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public static final class WrappedContextResolverCredentialsProvider {
/**
* Our {@link ContextResolver}
*/
@NonNull
private final ContextResolver resolver;
/**
* Our {@link CredentialsProvider}
*/
@NonNull
private final CredentialsProvider provider;
/**
* Our constructor.
*
* @param resolver the {@link ContextResolver}
* @param provider the {@link CredentialsProvider}
*/
public WrappedContextResolverCredentialsProvider(@NonNull ContextResolver resolver,
@NonNull CredentialsProvider provider) {
this.resolver = resolver;
this.provider = provider;
}
/**
* Stapler web binding for the {@link ModelObject} representing the context of the store.
*
* @param token the {@link ContextResolver#getToken(ModelObject)} of the context of the store.
* @return the {@link WrappedContextResolverCredentialsProvider} or {@code null}
*/
public WrappedCredentialsStore getContext(String token) {
ModelObject context = resolver.getContext(token);
if (context != null) {
CredentialsStore store = provider.getStore(context);
if (store != null) {
return new WrappedCredentialsStore(resolver, provider, token, store);
}
}
return null;
}
}
/**
* Stapler binding for a {@link CredentialsStore}.
*
* @since 2.0
*/
@Restricted(NoExternalUse.class)
public static final class WrappedCredentialsStore implements IconSpec, ModelObject {
/**
* Our {@link ContextResolver}
*/
@NonNull
private final ContextResolver resolver;
/**
* Our {@link CredentialsProvider}
*/
@NonNull
private final CredentialsProvider provider;
/**
* Our context's {@link ContextResolver#getToken(ModelObject)}.
*/
@NonNull
private final String token;
/**
* Our {@link CredentialsStore}.
*/
@NonNull
private final CredentialsStore store;
/**
* Our constructor.
*
* @param resolver the {@link ContextResolver}
* @param provider the {@link CredentialsProvider}
* @param token the context's {@link ContextResolver#getToken(ModelObject)}.
* @param store the {@link CredentialsStore}
*/
public WrappedCredentialsStore(@NonNull ContextResolver resolver, @NonNull CredentialsProvider provider,
@NonNull String token, @NonNull CredentialsStore store) {
this.store = store;
this.resolver = resolver;
this.provider = provider;
this.token = token;
}
/**
* Stapler web binding for adding credentials to the domain.
*
* @param req the request.
* @param rsp the response.
* @throws IOException if something goes wrong.
* @throws ServletException if something goes wrong.
*/
@RequirePOST
@Restricted(NoExternalUse.class)
public JSONObject doAddCredentials(StaplerRequest2 req, StaplerResponse2 rsp) throws IOException, ServletException {
store.checkPermission(CredentialsStoreAction.CREATE);
JSONObject data = req.getSubmittedForm();
String domainName = data.getString("domain");
CredentialsStoreAction.DomainWrapper wrapper = getWrappers().get(domainName);
if (!store.getDomains().contains(wrapper.getDomain())) {
hudson.util.HttpResponses.status(400).generateResponse(req, rsp, null);
return new JSONObject()
.element("message", "Store does not have selected domain")
.element("notificationType", "ERROR");
}
store.checkPermission(CredentialsStoreAction.CREATE);
boolean credentialsWereAdded;
try {
Credentials credentials = Descriptor.bindJSON(req, Credentials.class,
data.getJSONObject("credentials"));
credentialsWereAdded = store.addCredentials(wrapper.getDomain(), credentials);
} catch (LinkageError e) {
/*
* Descriptor#newInstanceImpl throws a LinkageError if the DataBoundConstructor or any DataBoundSetter
* throw any exception other than RuntimeException implementing HttpResponse.
*
* Checked exceptions implementing HttpResponse like FormException are wrapped and
* rethrown as HttpResponseException (a RuntimeException implementing HttpResponse) in
* RequestImpl#invokeConstructor.
*
* This approach is taken to maintain backward compatibility, as throwing a FormException directly
* from the constructor would result in a source-incompatible change, potentially breaking dependent plugins.
*
* Here, known exceptions are caught specifically to provide meaningful error response.
*/
Throwable rootCause = ExceptionUtils.getRootCause(e);
if (rootCause instanceof IOException || rootCause instanceof IllegalArgumentException
|| rootCause instanceof GeneralSecurityException) {
LOGGER.log(Level.WARNING, "Failed to create Credentials", e);
return new JSONObject().element("message", rootCause.getMessage()).element("notificationType",
"ERROR");
}
throw e;
}
if (credentialsWereAdded) {
return new JSONObject()
.element("message", "Credentials created")
.element("notificationType", "SUCCESS");
} else {
return new JSONObject()
.element("message", "Credentials with specified ID already exist in " + domainName + " domain")
// TODO: or domain does not exist at all?
.element("notificationType", "ERROR");
}
}
/**
* Returns a {@link CredentialsStoreAction.DomainWrapper} to use for contextualizing the credentials form.
*
* @return a {@link CredentialsStoreAction.DomainWrapper} to use for contextualizing the credentials form.
*/
public CredentialsStoreAction.DomainWrapper getWrapper() {
Collection<CredentialsStoreAction.DomainWrapper> values = getWrappers().values();
return values.isEmpty() ? null : values.iterator().next();
}
/**
* {@inheritDoc}
*/
@Override
public String getIconClassName() {
return store.getProvider().getIconClassName();
}
/**
* {@inheritDoc}
*/
@Override
public String getDisplayName() {
return store.getContextDisplayName();
}
/**
* Exposes the description of this store (i.e. the {@link CredentialsProvider#getDisplayName()}.
*
* @return the description of this store (i.e. the {@link CredentialsProvider#getDisplayName()}.
*/
public String getDescription() {
return store.getProvider().getDisplayName();
}
/**
* Exposes our URL (as we will be invoked from an unknown page so we need an absolute URL).
*
* @return our URL.
*/
public String getUrl() {
return String.format(
"%sdescriptor/%s/resolver/%s/provider/%s/context/%s",
Jenkins.get().getRootUrlFromRequest(),
CredentialsSelectHelper.class.getName(),
Util.rawEncode(resolver.getClass().getName()),
Util.rawEncode(provider.getClass().getName()),
Util.rawEncode(token)
);
}
/**
* Exposes the {@link CredentialsDescriptor} instances appropriate for this {@link CredentialsStore}.
*
* @return the {@link CredentialsDescriptor} instances appropriate for this {@link CredentialsStore}.
*/
public List<CredentialsDescriptor> getCredentialsDescriptors() {
return store.getCredentialsDescriptors();
}
/**
* The {@link CredentialsStoreAction.DomainWrapper} instances.
*
* @return the {@link CredentialsStoreAction.DomainWrapper} instances.
*/
public Map<String, CredentialsStoreAction.DomainWrapper> getWrappers() {
CredentialsStoreAction action = store.getStoreAction();
return action != null ? action.getDomains() : new CredentialsStoreAction() {
/**
* {@inheritDoc}
*/
@NonNull
@Override
public CredentialsStore getStore() {
return store;
}
}.getDomains();
}
/**
* The backing {@link CredentialsStore}.
* @return backing {@link CredentialsStore}.
* @since 2.1.5
*/
public CredentialsStore getStore() {
return store;
}
}
/**
* An extension point to allow plugging in additional resolution of {@link ModelObject} instances.
*
* @since 2.0
*/
public static abstract class ContextResolver implements ExtensionPoint {
/**
* A {@link ContextResolver} that can be used as a marker.
*
* @since 2.1.1
*/
public static final ContextResolver NONE = new ContextResolver() {
/**
* {@inheritDoc}
*/
@Override
public String getToken(ModelObject context) {
return null;
}
/**
* {@inheritDoc}
*/
@Override
public ModelObject getContext(String token) {
return null;
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public String getDisplayName() {
return "Nothing";
}
};
/**
* Maps a context object (a {@link ModelObject}) into a token that can be used to recover the context.
*
* @param context the {@link ModelObject}.
* @return a token if this {@link ContextResolver} can recover the object or {@code null} if the
* {@link ModelObject} type is not supported by this {@link ContextResolver}.
*/
@CheckForNull
public abstract String getToken(ModelObject context);
/**
* Maps a token from {@link #getToken(ModelObject)} back to its original {@link ModelObject}.
*
* @param token the token.
* @return the corresponding {@link ModelObject} or {@code null} if the object no longer exists or if the
* user does not have permission to access that object.
*/
@CheckForNull
public abstract ModelObject getContext(String token);
/**
* Returns a human readable description of the type of context objects that this resolver resolves.
* @return a human readable description of the type of context objects that this resolver resolves.
* @throws AbstractMethodError if somebody compiled against pre-2.1.1 implementations. Use
* {@link CredentialsSelectHelper.ContextResolver#displayName(CredentialsSelectHelper.ContextResolver)}
* if you would prefer not to have to catch them.
* @since 2.1.1
*/
@NonNull
public abstract String getDisplayName();
/**
* Returns a human readable description of the type of context objects that the specified resolver resolves.
*
* @param resolver the context resolver to get the display name of.
* @return a human readable description of the type of context objects that the specified resolver resolves.
* @since 2.1.1
*/
public static String displayName(ContextResolver resolver) {
try {
return resolver.getDisplayName();
} catch (AbstractMethodError e) {
// should not get here as do not anticipate new implementations that cannot target 2.1.1 as a baseline
return resolver.getClass().getName();
}
}
}
/**
* A {@link ContextResolver} for {@link Jenkins}.
*
* @since 2.0
*/
@Extension(ordinal = 1000)
public static class SystemContextResolver extends ContextResolver {
/**
* {@inheritDoc}
*/
@Override
public String getToken(ModelObject context) {
return context instanceof Jenkins ? "jenkins" : null;
}
/**
* {@inheritDoc}
*/
@Override
public ModelObject getContext(String token) {
return "jenkins".equals(token) ? Jenkins.get() : null;
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public String getDisplayName() {
return "Jenkins";
}
}
/**
* A {@link ContextResolver} for {@link Item} instances resolvable by {@link Jenkins#getItemByFullName(String)}.
*
* @since 2.0
*/
@Extension
public static class ItemContextResolver extends ContextResolver {
/**
* {@inheritDoc}
*/
@Override
public String getToken(ModelObject context) {
return context instanceof Item ? ((Item) context).getFullName() : null;
}
/**
* {@inheritDoc}
*/
@Override
public ModelObject getContext(String token) {
return Jenkins.get().getItemByFullName(token);
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public String getDisplayName() {
return "Items";
}
}
/**
* A {@link ContextResolver} for {@link User} instances.
*
* @since 2.0
*/
@Extension
public static class UserContextResolver extends ContextResolver {
/**
* {@inheritDoc}
*/
@Override
public String getToken(ModelObject context) {
return context instanceof User ? ((User) context).getId() : null;
}
/**
* {@inheritDoc}
*/
@Override
public ModelObject getContext(String token) {
return User.getById(token, false);
}
/**
* {@inheritDoc}
*/
@NonNull
@Override
public String getDisplayName() {
return "Users";
}
}
}