forked from jenkinsci/github-plugin
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGitHubServerConfig.java
More file actions
418 lines (375 loc) · 13.9 KB
/
GitHubServerConfig.java
File metadata and controls
418 lines (375 loc) · 13.9 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
package org.jenkinsci.plugins.github.config;
import com.cloudbees.plugins.credentials.CredentialsMatchers;
import com.cloudbees.plugins.credentials.common.StandardListBoxModel;
import com.google.common.base.Function;
import com.google.common.base.Optional;
import com.google.common.base.Predicate;
import com.google.common.base.Supplier;
import edu.umd.cs.findbugs.annotations.CheckForNull;
import edu.umd.cs.findbugs.annotations.NonNull;
import hudson.Extension;
import hudson.Util;
import hudson.model.AbstractDescribableImpl;
import hudson.model.Descriptor;
import hudson.security.ACL;
import hudson.security.Permission;
import hudson.util.FormValidation;
import hudson.util.ListBoxModel;
import hudson.util.Secret;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import jenkins.model.Jenkins;
import jenkins.scm.api.SCMName;
import org.apache.commons.lang3.StringUtils;
import org.jenkinsci.plugins.github.internal.GitHubLoginFunction;
import org.jenkinsci.plugins.github.util.misc.NullSafeFunction;
import org.jenkinsci.plugins.github.util.misc.NullSafePredicate;
import org.jenkinsci.plugins.plaincredentials.StringCredentials;
import org.kohsuke.accmod.Restricted;
import org.kohsuke.accmod.restrictions.DoNotUse;
import org.kohsuke.github.GitHub;
import org.kohsuke.stapler.DataBoundConstructor;
import org.kohsuke.stapler.DataBoundSetter;
import org.kohsuke.stapler.QueryParameter;
import org.kohsuke.stapler.interceptor.RequirePOST;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import static com.cloudbees.plugins.credentials.CredentialsProvider.findCredentialByIdInItemGroup;
import static com.cloudbees.plugins.credentials.domains.URIRequirementBuilder.fromUri;
import static org.apache.commons.lang3.StringUtils.defaultIfBlank;
import static org.apache.commons.lang3.StringUtils.defaultIfEmpty;
import static org.apache.commons.lang3.StringUtils.isNotBlank;
/**
* This object represents configuration of each credentials-github pair.
* If no api url explicitly defined, default url used.
* So one github server can be used with many creds and one token can be used multiply times in lot of gh servers
*
* @author lanwen (Merkushev Kirill)
* @since 1.13.0
*/
public class GitHubServerConfig extends AbstractDescribableImpl<GitHubServerConfig> {
private static final Logger LOGGER = LoggerFactory.getLogger(GitHubServerConfig.class);
/**
* Common prefixes that we should remove when inferring a {@link #name}.
*
* @since 1.28.0
*/
private static final String[] COMMON_PREFIX_HOSTNAMES = {
"git.",
"github.",
"vcs.",
"scm.",
"source."
};
/**
* Because of {@link GitHub} hide this const from external use we need to store it here
*/
public static final String GITHUB_URL = "https://api.github.com";
/**
* The name to display for the public GitHub service.
*
* @since 1.28.0
*/
private static final String PUBLIC_GITHUB_NAME = "GitHub";
/**
* Used as default token value if no any creds found by given credsId.
*/
private static final String UNKNOWN_TOKEN = "UNKNOWN_TOKEN";
/**
* Default value in MB for client cache size
*
* @see #getClientCacheSize()
*/
public static final int DEFAULT_CLIENT_CACHE_SIZE_MB = 20;
/**
* The optional display name of this server.
*/
@CheckForNull
private String name;
private String apiUrl = GITHUB_URL;
private boolean manageHooks = true;
private final String credentialsId;
/**
* @see #getClientCacheSize()
* @see #setClientCacheSize(int)
*/
private int clientCacheSize = DEFAULT_CLIENT_CACHE_SIZE_MB;
/**
* To avoid creation of new one on every login with this config
*/
private transient GitHub cachedClient;
@DataBoundConstructor
public GitHubServerConfig(String credentialsId) {
this.credentialsId = credentialsId;
}
/**
* Sets the optional display name.
* @param name the optional display name.
*/
@DataBoundSetter
public void setName(@CheckForNull String name) {
this.name = Util.fixEmptyAndTrim(name);
}
/**
* Set the API endpoint.
*
* @param apiUrl custom url if GH. Default value will be used in case of custom is unchecked or value is blank
*/
@DataBoundSetter
public void setApiUrl(String apiUrl) {
this.apiUrl = defaultIfBlank(apiUrl, GITHUB_URL);
}
/**
* This server config will be used to manage GH Hooks if true
*
* @param manageHooks false to ignore this config on hook auto-management
*/
@DataBoundSetter
public void setManageHooks(boolean manageHooks) {
this.manageHooks = manageHooks;
}
/**
* This method was introduced to hide custom api url under checkbox, but now UI simplified to show url all the time
* see jenkinsci/github-plugin/pull/112 for more details
*
* @param customApiUrl ignored
*
* @deprecated simply remove usage of this method, it ignored now. Should be removed after 20 sep 2016.
*/
@Deprecated
public void setCustomApiUrl(boolean customApiUrl) {
}
/**
* Gets the optional display name of this server.
*
* @return the optional display name of this server, may be empty or {@code null} but best effort is made to ensure
* that it has some meaningful text.
* @since 1.28.0
*/
public String getName() {
return name;
}
/**
* Gets the formatted display name (which will always include the api url)
*
* @return the formatted display name.
* @since 1.28.0
*/
public String getDisplayName() {
String gitHubName = getName();
boolean isGitHubCom = StringUtils.isBlank(apiUrl) || GITHUB_URL.equals(apiUrl);
if (StringUtils.isBlank(gitHubName)) {
gitHubName = isGitHubCom ? PUBLIC_GITHUB_NAME : SCMName.fromUrl(apiUrl, COMMON_PREFIX_HOSTNAMES);
}
String gitHubUrl = isGitHubCom ? "https://github.com" : StringUtils.removeEnd(apiUrl, "/api/v3");
return StringUtils.isBlank(gitHubName)
? gitHubUrl
: Messages.GitHubServerConfig_displayName(gitHubName, gitHubUrl);
}
public String getApiUrl() {
return apiUrl;
}
public boolean isManageHooks() {
return manageHooks;
}
public String getCredentialsId() {
return credentialsId;
}
/**
* Capacity of cache for GitHub client in MB.
*
* Defaults to 20 MB
*
* @since 1.14.0
*/
public int getClientCacheSize() {
return clientCacheSize;
}
/**
* @param clientCacheSize capacity of cache for GitHub client in MB, set to <= 0 to turn off this feature
*/
@DataBoundSetter
public void setClientCacheSize(int clientCacheSize) {
this.clientCacheSize = clientCacheSize;
}
/**
* @return cached GH client or null
*/
protected synchronized GitHub getCachedClient() {
return cachedClient;
}
/**
* Used by {@link org.jenkinsci.plugins.github.config.GitHubServerConfig.ClientCacheFunction}
*
* @param cachedClient updated client. Maybe null to invalidate cache
*/
protected synchronized void setCachedClient(GitHub cachedClient) {
this.cachedClient = cachedClient;
}
/**
* Checks GH url for equality to default api url
*
* @param apiUrl should be not blank and not equal to default url to return true
*
* @return true if url not blank and not equal to default
*/
public static boolean isUrlCustom(String apiUrl) {
return isNotBlank(apiUrl) && !GITHUB_URL.equals(apiUrl);
}
/**
* Converts server config to authorized GH instance. If login process is not successful it returns null
*
* @return function to convert config to gh instance
* @see org.jenkinsci.plugins.github.config.GitHubServerConfig.ClientCacheFunction
*/
@CheckForNull
public static Function<GitHubServerConfig, GitHub> loginToGithub() {
return new ClientCacheFunction();
}
/**
* Extracts token from secret found by {@link #secretFor(String)}
* Returns {@link #UNKNOWN_TOKEN} if no any creds secret found with this id.
*
* @param credentialsId id to find creds
*
* @return token from creds or default non empty string
*/
@NonNull
public static String tokenFor(String credentialsId) {
return secretFor(credentialsId).or(new Supplier<Secret>() {
@Override
public Secret get() {
return Secret.fromString(UNKNOWN_TOKEN);
}
}).getPlainText();
}
/**
* Tries to find {@link StringCredentials} by id and returns secret from it.
*
* @param credentialsId id to find creds
*
* @return secret from creds or empty optional
*/
@NonNull
public static Optional<Secret> secretFor(String credentialsId) {
if (credentialsId == null) {
return Optional.absent();
}
var creds = findCredentialByIdInItemGroup(credentialsId, StringCredentials.class, null, null, null);
if (creds == null) {
return Optional.absent();
}
return Optional.of(creds.getSecret());
}
/**
* Returns true if given host is part of stored (or default if blank) api url
*
* For example:
* withHost(api.github.com).apply(config for ~empty~) = true
* withHost(api.github.com).apply(config for api.github.com) = true
* withHost(api.github.com).apply(config for github.company.com) = false
*
* @param host host to find in api url
*
* @return predicate to match against {@link GitHubServerConfig}
*/
public static Predicate<GitHubServerConfig> withHost(final String host) {
return new NullSafePredicate<GitHubServerConfig>() {
@Override
protected boolean applyNullSafe(@NonNull GitHubServerConfig github) {
return defaultIfEmpty(github.getApiUrl(), GITHUB_URL).contains(host);
}
};
}
/**
* Returns true if config can be used in hooks managing
*
* @return predicate to match against {@link GitHubServerConfig}
*/
public static Predicate<GitHubServerConfig> allowedToManageHooks() {
return new NullSafePredicate<GitHubServerConfig>() {
@Override
protected boolean applyNullSafe(@NonNull GitHubServerConfig github) {
return github.isManageHooks();
}
};
}
@Extension
public static class DescriptorImpl extends Descriptor<GitHubServerConfig> {
@Override
public String getDisplayName() {
return "GitHub Server";
}
@NonNull
@Override
public Permission getRequiredGlobalConfigPagePermission() {
return Jenkins.MANAGE;
}
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String apiUrl,
@QueryParameter String credentialsId) {
if (!Jenkins.getInstance().hasPermission(Jenkins.MANAGE)) {
return new StandardListBoxModel().includeCurrentValue(credentialsId);
}
return new StandardListBoxModel()
.includeEmptyValue()
.includeMatchingAs(ACL.SYSTEM,
Jenkins.getInstance(),
StringCredentials.class,
fromUri(defaultIfBlank(apiUrl, GITHUB_URL)).build(),
CredentialsMatchers.always()
);
}
@RequirePOST
@Restricted(DoNotUse.class) // WebOnly
@SuppressWarnings("unused")
public FormValidation doVerifyCredentials(
@QueryParameter String apiUrl,
@QueryParameter String credentialsId) throws IOException {
Jenkins.getActiveInstance().checkPermission(Jenkins.MANAGE);
GitHubServerConfig config = new GitHubServerConfig(credentialsId);
config.setApiUrl(apiUrl);
config.setClientCacheSize(0);
GitHub gitHub = new GitHubLoginFunction().apply(config);
try {
if (gitHub != null && gitHub.isCredentialValid()) {
return FormValidation.ok("Credentials verified for user %s, rate limit: %s",
gitHub.getMyself().getLogin(), gitHub.getRateLimit().remaining);
} else {
return FormValidation.error("Failed to validate the account");
}
} catch (IOException e) {
return FormValidation.error(e, "Failed to validate the account");
}
}
@SuppressWarnings("unused")
public FormValidation doCheckApiUrl(@QueryParameter String value) {
try {
new URL(value);
} catch (MalformedURLException e) {
return FormValidation.error("Malformed GitHub url (%s)", e.getMessage());
}
if (GITHUB_URL.equals(value)) {
return FormValidation.ok();
}
if (value.endsWith("/api/v3") || value.endsWith("/api/v3/")) {
return FormValidation.ok();
}
return FormValidation.warning("GitHub Enterprise API URL ends with \"/api/v3\"");
}
}
/**
* Function to get authorized GH client and cache it in config
* has {@link #loginToGithub()} static factory
*/
private static class ClientCacheFunction extends NullSafeFunction<GitHubServerConfig, GitHub> {
@Override
protected GitHub applyNullSafe(@NonNull GitHubServerConfig github) {
if (github.getCachedClient() == null) {
github.setCachedClient(new GitHubLoginFunction().apply(github));
}
return github.getCachedClient();
}
}
}