下面列出了hudson.model.ModelObject#org.jenkinsci.plugins.plaincredentials.StringCredentials 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@SuppressWarnings("unused")
public ListBoxModel doFillCredentialsIdItems(@QueryParameter final String credentialsId) {
Jenkins instance = Jenkins.get();
if (!instance.hasPermission(Jenkins.ADMINISTER)) {
return new StandardListBoxModel().includeCurrentValue(credentialsId);
}
return new StandardListBoxModel()
.includeEmptyValue()
.includeMatchingAs(
ACL.SYSTEM,
instance,
StringCredentials.class,
URIRequirementBuilder.fromUri(ATLASSIAN_API_URL).build(),
CredentialsMatchers.always());
}
@RequirePOST
public ListBoxModel doFillKubernetesCredentialsIdItems() {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
return new StandardListBoxModel().withEmptySelection()
.withMatching(
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(FileCredentials.class),
CredentialsMatchers.instanceOf(TokenProducer.class),
CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)),
CredentialsProvider.lookupCredentials(StandardCredentials.class,
Jenkins.get(),
ACL.SYSTEM,
Collections.EMPTY_LIST
));
}
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@QueryParameter String serverUrl) {
Jenkins.get().checkPermission(Jenkins.ADMINISTER);
return new StandardListBoxModel().withEmptySelection()
.withMatching(
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(FileCredentials.class),
CredentialsMatchers.instanceOf(TokenProducer.class),
CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)),
CredentialsProvider.lookupCredentials(StandardCredentials.class,
Jenkins.get(),
ACL.SYSTEM,
serverUrl != null ? URIRequirementBuilder.fromUri(serverUrl).build()
: Collections.EMPTY_LIST
));
}
private String getgApiKey() {
StandardCredentials credentials = null;
try {
credentials = CredentialsMatchers.firstOrNull(
lookupCredentials(StandardCredentials.class, (Item) null, ACL.SYSTEM, new ArrayList<DomainRequirement>()),
CredentialsMatchers.withId(gApiKeyID));
}
catch (NullPointerException e) {
throw new ConnectionException(SR.getString("api.key.not.set"));
}
if (credentials != null) {
if (credentials instanceof StringCredentials) {
return ((StringCredentials) credentials).getSecret().getPlainText();
}
}
throw new IllegalStateException("Could not find Acunetix API Key ID: " + gApiKeyID);
}
public ListBoxModel doFillGApiKeyIDItems(
@AncestorInPath Item item) {
StandardListBoxModel result = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return result.includeCurrentValue(gApiKeyID);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ)
&& !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return result.includeCurrentValue(gApiKeyID);
}
}
if (gApiKeyID != null) {
result.includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.withId(gApiKeyID)));
}
return result
.includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.instanceOf(StringCredentials.class)));
}
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
final Item item, final String credentialsId, final String uri) {
final StandardListBoxModel result = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return result.includeCurrentValue(credentialsId);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ)
&& !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return result.includeCurrentValue(credentialsId);
}
}
return result //
.includeEmptyValue() //
.includeMatchingAs(
item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
item,
StandardCredentials.class,
URIRequirementBuilder.fromUri(uri).build(),
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)))
.includeCurrentValue(credentialsId);
}
public static Optional<StandardCredentials> findCredentials(
final Item item, final String credentialsId, final String uri) {
if (isNullOrEmpty(credentialsId)) {
return absent();
}
return fromNullable(
CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StandardCredentials.class,
item,
item instanceof Queue.Task
? Tasks.getAuthenticationOf((Queue.Task) item)
: ACL.SYSTEM,
URIRequirementBuilder.fromUri(uri).build()),
CredentialsMatchers.allOf(
CredentialsMatchers.withId(credentialsId),
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
/**
* Construct a Marathon client based on the provided credentialsId and execute an update for the configuration's
* Marathon application.
*
* @param credentialsId A string ID for a credential within Jenkin's Credential store
* @throws MarathonException thrown if the Marathon service has an error
*/
private void doUpdate(final String credentialsId) throws MarathonException {
final Credentials credentials = MarathonBuilderUtils.getJenkinsCredentials(credentialsId, Credentials.class);
Marathon client;
if (credentials instanceof UsernamePasswordCredentials) {
client = getMarathonClient((UsernamePasswordCredentials) credentials);
} else if (credentials instanceof StringCredentials) {
client = getMarathonClient((StringCredentials) credentials);
} else {
client = getMarathonClient();
}
if (client != null) {
client.updateApp(getApp().getId(), getApp(), config.getForceUpdate());
}
}
/**
* Get a Marathon client with Authorization headers using the token within provided credentials. If the content of
* credentials is JSON, this will use the "jenkins_token" field; if the content is just a string, that will be
* used as the token value.
*
* @param credentials String credentials
* @return Marathon client with token in auth header
*/
private Marathon getMarathonClient(StringCredentials credentials) {
String token;
try {
final JSONObject json = JSONObject.fromObject(credentials.getSecret().getPlainText());
if (json.has("jenkins_token")) {
token = json.getString("jenkins_token");
} else {
token = "";
}
} catch (JSONException jse) {
token = credentials.getSecret().getPlainText();
}
if (StringUtils.isNotEmpty(token)) {
return MarathonClient
.getInstanceWithTokenAuth(getURL(), token);
}
return getMarathonClient();
}
/**
* Test that a JSON credential without a "jenkins_token" field and without a proper DC/OS service account value
* results in a 401 and only 1 web request.
*
* @throws Exception
*/
@Test
public void testRecorderInvalidToken() throws Exception {
final FreeStyleProject project = j.createFreeStyleProject();
final SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
final CredentialsStore systemStore = system.getStore(j.getInstance());
final String credentialValue = "{\"field1\":\"some value\"}";
final Secret secret = Secret.fromString(credentialValue);
final StringCredentials credential = new StringCredentialsImpl(CredentialsScope.GLOBAL, "invalidtoken", "a token for JSON token test", secret);
TestUtils.enqueueFailureResponse(httpServer, 401);
systemStore.addCredentials(Domain.global(), credential);
addBuilders(TestUtils.loadFixture("idonly.json"), project);
// add post-builder
addPostBuilders(project, "invalidtoken");
final FreeStyleBuild build = j.assertBuildStatus(Result.FAILURE, project.scheduleBuild2(0).get());
j.assertLogContains("[Marathon] Authentication to Marathon instance failed:", build);
j.assertLogContains("[Marathon] Invalid DC/OS service account JSON", build);
assertEquals("Only 1 request should have been made.", 1, httpServer.getRequestCount());
}
@SuppressFBWarnings("NP_NULL_PARAM_DEREF")
public static ListBoxModel doFillCredentialsIdItems(
final Item item, final String credentialsId, final String uri) {
final StandardListBoxModel result = new StandardListBoxModel();
if (item == null) {
if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
return result.includeCurrentValue(credentialsId);
}
} else {
if (!item.hasPermission(Item.EXTENDED_READ)
&& !item.hasPermission(CredentialsProvider.USE_ITEM)) {
return result.includeCurrentValue(credentialsId);
}
}
return result //
.includeEmptyValue() //
.includeMatchingAs(
item instanceof Queue.Task ? Tasks.getAuthenticationOf((Queue.Task) item) : ACL.SYSTEM,
item,
StandardCredentials.class,
URIRequirementBuilder.fromUri(uri).build(),
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)))
.includeCurrentValue(credentialsId);
}
public static Optional<StandardCredentials> findCredentials(
final Item item, final String credentialsId, final String uri) {
if (isNullOrEmpty(credentialsId)) {
return absent();
}
return fromNullable(
CredentialsMatchers.firstOrNull(
CredentialsProvider.lookupCredentials(
StandardCredentials.class,
item,
item instanceof Queue.Task
? Tasks.getAuthenticationOf((Queue.Task) item)
: ACL.SYSTEM,
URIRequirementBuilder.fromUri(uri).build()),
CredentialsMatchers.allOf(
CredentialsMatchers.withId(credentialsId),
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
@Restricted(NoExternalUse.class)
private String getApiToken(String apiTokenId, Item item) {
ItemGroup<?> context = null != item ? item.getParent() : Jenkins.get();
StandardCredentials credentials = CredentialsMatchers.firstOrNull(
lookupCredentials(
StandardCredentials.class,
context,
ACL.SYSTEM,
URIRequirementBuilder.fromUri(url).build()),
CredentialsMatchers.withId(apiTokenId));
if (credentials != null) {
if (credentials instanceof GitLabApiToken) {
return ((GitLabApiToken) credentials).getApiToken().getPlainText();
}
if (credentials instanceof StringCredentials) {
return ((StringCredentials) credentials).getSecret().getPlainText();
}
}
throw new IllegalStateException("No credentials found for credentialsId: " + apiTokenId);
}
public Optional<String> getSecretFor(final String credentialsId) {
final List<StringCredentials> credentials =
CredentialsProvider.lookupCredentials(
StringCredentials.class,
Jenkins.get(),
ACL.SYSTEM,
Collections.emptyList());
final CredentialsMatcher matcher = CredentialsMatchers.withId(credentialsId);
return Optional.ofNullable(CredentialsMatchers.firstOrNull(credentials, matcher))
.flatMap(creds -> Optional.ofNullable(creds.getSecret()))
.flatMap(secret -> Optional.ofNullable(secret.getPlainText()));
}
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item item) {
return new StandardListBoxModel().withEmptySelection().withMatching(
CredentialsMatchers.anyOf(
CredentialsMatchers.instanceOf(StringCredentials.class),
CredentialsMatchers.instanceOf(UsernamePasswordCredentials.class)
),
CredentialsProvider.lookupCredentials(StandardCredentials.class, item, null, Collections.<DomainRequirement>emptyList())
);
}
public DcosAuthImpl(final StringCredentials credentials) {
this(
credentials,
new JWTSigner.Options(),
ContentType.APPLICATION_JSON,
HttpClientBuilder.create(),
new HttpClientContext()
);
}
DcosAuthImpl(final StringCredentials credentials,
final JWTSigner.Options options,
final ContentType contentType,
final HttpClientBuilder clientBuilder,
final HttpClientContext clientContext) {
this.options = options;
this.contentType = contentType;
this.client = clientBuilder;
this.context = clientContext;
this.credentials = credentials;
}
@Override
public boolean updateTokenCredentials(final Credentials tokenCredentials) throws AuthenticationException {
if (tokenCredentials instanceof StringCredentials) {
final StringCredentials oldCredentials = (StringCredentials) tokenCredentials;
if (credentials != null) {
try {
final String token = getToken();
if (token == null) {
// TODO: better message somewhere in getToken flow of what happened?
final String errorMessage = "Failed to retrieve authentication token from DC/OS.";
LOGGER.warning(errorMessage);
throw new AuthenticationException(errorMessage);
}
final StringCredentials updatedCredentials = newTokenCredentials(oldCredentials, token);
return doTokenUpdate(oldCredentials.getId(), updatedCredentials);
} catch (IOException e) {
LOGGER.warning(e.getMessage());
throw new AuthenticationException(e.getMessage());
}
}
} else {
LOGGER.warning("Invalid credential type, expected String Credentials, received: " + tokenCredentials.getClass().getName());
}
return false;
}
public static TokenAuthProvider getTokenAuthProvider(final Providers provider, final Credentials credentials) {
switch (provider) {
case DCOS:
return new DcosAuthImpl((StringCredentials) credentials);
default:
return null;
}
}
/**
* Helper method to update tokenCredentials with contents of creds.
* <p>
* This searches all domains for the id associated with tokenCredentials and updates the first credential it finds.
*
* @param tokenId Existing credentials that should be updated.
* @param creds New credentials
* @throws IOException If problems reading or writing to Jenkins Credential Store
*/
boolean doTokenUpdate(final String tokenId, final Credentials creds) throws IOException {
final SystemCredentialsProvider.ProviderImpl systemProvider = ExtensionList.lookup(CredentialsProvider.class)
.get(SystemCredentialsProvider.ProviderImpl.class);
if (systemProvider == null) return false;
final CredentialsStore credentialsStore = systemProvider.getStore(Jenkins.getInstance());
if (credentialsStore == null) return false;
/*
Walk through all domains and credentials for each domain to find a credential with the matching id.
*/
for (final Domain d : credentialsStore.getDomains()) {
for (Credentials c : credentialsStore.getCredentials(d)) {
if (!(c instanceof StringCredentials)) continue;
final StringCredentials stringCredentials = (StringCredentials) c;
if (stringCredentials.getId().equals(tokenId)) {
final boolean wasUpdated = credentialsStore.updateCredentials(d, c, creds);
if (!wasUpdated) {
LOGGER.warning("Updating Token credential failed during update call.");
}
return wasUpdated;
}
}
}
// if the credential was not found, then put a warning in the console log.
LOGGER.warning("Token credential was not found in the Credentials Store.");
return false;
}
/**
* Perform the actual update call to Marathon. If a 401 (Unauthenticated) response is received,
* this will try to retrieve a new token from DC/OS using JWT credentials.
*
* @return this Marathon builder
* @throws MarathonException If Marathon does not return a 20x OK response
* @throws AuthenticationException If an authentication provider was used and encountered a problem.
*/
@Override
public MarathonBuilder update() throws MarathonException, AuthenticationException {
if (getApp() != null) {
try {
doUpdate(config.getCredentialsId());
} catch (MarathonException marathonException) {
LOGGER.warning("Marathon Exception: " + marathonException.getMessage());
// 401 results may be possible to resolve, others not so much
if (marathonException.getStatus() != 401) throw marathonException;
LOGGER.fine("Received 401 when updating Marathon application.");
final StringCredentials tokenCredentials = MarathonBuilderUtils.getTokenCredentials(config.getCredentialsId());
if (tokenCredentials == null) {
LOGGER.warning("Unauthorized (401) and service account credentials are not filled in.");
throw marathonException;
}
// check if service account credentials were configured
// try to determine correct provider and update token
// (there is only one provider thus far, so this is simple)
boolean updatedToken = false;
final TokenAuthProvider provider = TokenAuthProvider.getTokenAuthProvider(TokenAuthProvider.Providers.DCOS, tokenCredentials);
if (provider != null) {
updatedToken = provider.updateTokenCredentials(tokenCredentials);
}
// use the new token if it was updated
if (updatedToken) {
LOGGER.info("Token was successfully updated.");
doUpdate(config.getCredentialsId());
}
}
}
return this;
}
/**
* Test a basic API token using StringCredentials.
*
* @throws Exception
*/
@Test
public void testRecorderBasicToken() throws Exception {
final FreeStyleProject project = j.createFreeStyleProject();
final String responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
final SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
final CredentialsStore systemStore = system.getStore(j.getInstance());
final String tokenValue = "my secret token";
final Secret secret = Secret.fromString(tokenValue);
final StringCredentials credential = new StringCredentialsImpl(CredentialsScope.GLOBAL, "basictoken", "a token for basic token test", secret);
TestUtils.enqueueJsonResponse(httpServer, responseStr);
systemStore.addCredentials(Domain.global(), credential);
// add builders
addBuilders(TestUtils.loadFixture("idonly.json"), project);
// add post-builder
addPostBuilders(project, "basictoken");
final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
j.assertLogContains("[Marathon]", build);
// handler assertions
assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
RecordedRequest request = httpServer.takeRequest();
final String authorizationText = request.getHeader("Authorization");
assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
/**
* Test that a JSON credential with "jenkins_token" uses the token value as the authentication token.
*
* @throws Exception
*/
@Test
public void testRecorderJSONToken() throws Exception {
final FreeStyleProject project = j.createFreeStyleProject();
final String responseStr = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
final SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
final CredentialsStore systemStore = system.getStore(j.getInstance());
final String tokenValue = "my secret token";
final String credentialValue = "{\"field1\":\"some value\", \"jenkins_token\":\"" + tokenValue + "\"}";
final Secret secret = Secret.fromString(credentialValue);
final StringCredentials credential = new StringCredentialsImpl(CredentialsScope.GLOBAL, "jsontoken", "a token for JSON token test", secret);
TestUtils.enqueueJsonResponse(httpServer, responseStr);
systemStore.addCredentials(Domain.global(), credential);
// add builders
addBuilders(TestUtils.loadFixture("idonly.json"), project);
// add post-builder
addPostBuilders(project, "jsontoken");
final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
j.assertLogContains("[Marathon]", build);
// handler assertions
assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
RecordedRequest request = httpServer.takeRequest();
final String authorizationText = request.getHeader("Authorization");
assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}
public static Optional<String> findSecretString(String credentialsId) {
Optional<String> token = Optional.empty();
if (!isNullOrEmpty(credentialsId)) {
final Optional<StringCredentials> credentials =
CredentialsHelper.findCredentials(credentialsId);
if (credentials.isPresent()) {
final StringCredentials stringCredential =
checkNotNull(credentials.get(), "Credentials selected but not set!");
token = Optional.of(stringCredential.getSecret().getPlainText());
}
}
return token;
}
public static Optional<StringCredentials> findCredentials(String apiTokenCredentialsId) {
if (isNullOrEmpty(apiTokenCredentialsId)) {
return Optional.empty();
}
return Optional.ofNullable(
firstOrNull(
getAllCredentials(StringCredentials.class), allOf(withId(apiTokenCredentialsId))));
}
@Override
public boolean matches(@NonNull Credentials credentials) {
try {
return credentials instanceof GitLabApiToken || credentials instanceof StringCredentials;
} catch (Throwable e) {
return false;
}
}
public static void jvctsPerform(
final ViolationsToGitHubConfig configUnexpanded,
final FilePath fp,
final Run<?, ?> build,
final TaskListener listener) {
final PrintStream logger = listener.getLogger();
try {
final EnvVars env = build.getEnvironment(listener);
final ViolationsToGitHubConfig configExpanded = expand(configUnexpanded, env);
logger.println("---");
logger.println("--- Jenkins Violation Comments to GitHub ---");
logger.println("---");
logConfiguration(configExpanded, build, listener);
final Optional<StandardCredentials> credentials =
findCredentials(
build.getParent(), configExpanded.getCredentialsId(), configExpanded.getGitHubUrl());
if (!isNullOrEmpty(configExpanded.getoAuth2Token())) {
logger.println("Using OAuth2Token");
} else if (credentials.isPresent()) {
final StandardCredentials standardCredentials = credentials.get();
if (standardCredentials instanceof StandardUsernamePasswordCredentials) {
logger.println("Using username / password");
} else if (standardCredentials instanceof StringCredentials) {
logger.println("Using OAuth2Token credential style");
}
} else {
throw new IllegalStateException("No credentials found!");
}
logger.println("Running Jenkins Violation Comments To GitHub");
logger.println("PR " + configExpanded.getPullRequestId());
fp.act(
new FileCallable<Void>() {
private static final long serialVersionUID = 6166111757469534436L;
@Override
public void checkRoles(final RoleChecker checker) throws SecurityException {}
@Override
public Void invoke(final File workspace, final VirtualChannel channel)
throws IOException, InterruptedException {
setupFindBugsMessages();
listener.getLogger().println("Workspace: " + workspace.getAbsolutePath());
doPerform(configExpanded, workspace, credentials.orNull(), listener);
return null;
}
});
} catch (final Exception e) {
Logger.getLogger(JvctgPerformer.class.getName()).log(SEVERE, "", e);
final StringWriter sw = new StringWriter();
e.printStackTrace(new PrintWriter(sw));
logger.println(sw.toString());
return;
}
}
public static ListBoxModel doFillApiTokenCredentialsIdItems() {
List<StringCredentials> credentials = getAllCredentials(StringCredentials.class);
return new StandardListBoxModel() //
.includeEmptyValue() //
.withAll(credentials);
}
@Override protected Class<StringCredentials> type() {
return StringCredentials.class;
}
@Override protected Class<StringCredentials> type() {
return StringCredentials.class;
}