org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl Java Examples

The following examples show how to use org.jenkinsci.plugins.plaincredentials.impl.StringCredentialsImpl. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: BuildWrapperOrderCredentialsBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-37871")
@Test public void secretBuildWrapperRunsBeforeNormalWrapper() throws Exception {
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample1", Secret.fromString(password));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding(bindingKey, credentialsId)));

    FreeStyleProject f = r.createFreeStyleProject("buildWrapperOrder");

    f.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo $PASS_1"));
    f.getBuildWrappersList().add(new BuildWrapperOrder());
    f.getBuildWrappersList().add(wrapper);

    // configRoundtrip makes sure the ordinal of SecretBuildWrapper extension is applied correctly.
    r.configRoundtrip(f);

    FreeStyleBuild b = r.buildAndAssertSuccess(f);
    r.assertLogContains("Secret found!", b);
}
 
Example #2
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-27486")
@Test public void masking() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            String credentialsId = "creds";
            String secret = "s3cr3t";
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "node {\n"
                    + "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'SECRET')]) {\n"
                    // forgot set +x, ran /usr/bin/env, etc.
                    + "    if (isUnix()) {sh 'echo $SECRET > oops'} else {bat 'echo %SECRET% > oops'}\n"
                    + "  }\n"
                    + "}", true));
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
            story.j.assertLogNotContains(secret, b);
            story.j.assertLogContains("echo ****", b);
        }
    });
}
 
Example #3
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-27389")
@Test public void grabEnv() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            String credentialsId = "creds";
            String secret = "s3cr3t";
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "def extract(id) {\n"
                    + "  def v\n"
                    + "  withCredentials([string(credentialsId: id, variable: 'temp')]) {\n"
                    + "    v = env.temp\n"
                    + "  }\n"
                    + "  v\n"
                    + "}\n"
                    + "node {\n"
                    + "  echo \"got: ${extract('" + credentialsId + "')}\"\n"
                    + "}", true));
            story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get()));
        }
    });
}
 
Example #4
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * 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());
}
 
Example #5
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test public void incorrectType() throws Exception {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            StringCredentialsImpl c = new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", "sample", Secret.fromString("s3cr3t"));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "node {\n"
                    + "  withCredentials([usernamePassword(usernameVariable: 'USERNAME', passwordVariable: 'PASSWORD', credentialsId: 'creds')]) {\n"
                    + "  }\n"
                    + "}", true));
            WorkflowRun r = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0).get());

            // make sure error message contains information about the actual type and the expected type
            story.j.assertLogNotContains("s3cr3t", r);
            story.j.assertLogContains(StandardUsernamePasswordCredentials.class.getName(), r); // no descriptor for the interface type
            story.j.assertLogContains(stringCredentialsDescriptor.getDisplayName(), r);
            story.j.assertLogNotContains("\tat ", r);
        }
    });
}
 
Example #6
Source File: SecretBuildWrapperTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("SECURITY-1374")
@Test public void maskingPostBuild() throws Exception {
    String credentialsId = "creds_1";
    String password = "p4$$";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample1", Secret.fromString(password));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Collections.singletonList(new StringBinding("PASS_1", credentialsId)));

    FreeStyleProject f = r.createFreeStyleProject();

    f.setConcurrentBuild(true);
    f.getBuildWrappersList().add(wrapper);
    Publisher publisher = new PasswordPublisher(password);
    f.getPublishersList().add(publisher);

    FreeStyleBuild b = r.buildAndAssertSuccess(f);
    r.assertLogNotContains(password, b);
    r.assertLogContains("****", b);
}
 
Example #7
Source File: GHRule.java    From github-integration-plugin with MIT License 6 votes vote down vote up
/**
 * Prepare global GitHub plugin configuration.
 * Nothing specific to job.
 */
public static GitHubServerConfig prepareGitHubPlugin() {
    // prepare global jRule settings
    final StringCredentialsImpl cred = new StringCredentialsImpl(
            CredentialsScope.GLOBAL,
            null,
            "description",
            Secret.fromString(GH_TOKEN)
    );

    SystemCredentialsProvider.getInstance().getCredentials().add(cred);

    final GitHubPluginConfig gitHubPluginConfig = GitHubPlugin.configuration();

    final List<GitHubServerConfig> gitHubServerConfigs = new ArrayList<>();
    final GitHubServerConfig gitHubServerConfig = new GitHubServerConfig(cred.getId());
    gitHubServerConfig.setManageHooks(false);
    gitHubServerConfig.setClientCacheSize(0);
    gitHubServerConfigs.add(gitHubServerConfig);

    gitHubPluginConfig.setConfigs(gitHubServerConfigs);

    return gitHubServerConfig;
}
 
Example #8
Source File: GitLabConnectionConfigSSLTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN_ID)));
        }
    }
}
 
Example #9
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-41760")
@Test public void emptyOrBlankCreds() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition("node {withCredentials([]) {echo 'normal output'}}", true));
            story.j.assertLogContains("normal output", story.j.buildAndAssertSuccess(p));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", null, Secret.fromString("")));
            p.setDefinition(new CpsFlowDefinition("node {withCredentials([string(variable: 'SECRET', credentialsId: 'creds')]) {echo 'normal output'}}", true));
            story.j.assertLogContains("normal output", story.j.buildAndAssertSuccess(p));
        }
    });
}
 
Example #10
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-38831")
@Test
public void testTrackingOfCredential() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            String credentialsId = "creds";
            String secret = "s3cr3t";
            StringCredentialsImpl credentials = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret));
            Fingerprint fingerprint = CredentialsProvider.getFingerprintOf(credentials);

            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), credentials);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
              + "def extract(id) {\n"
              + "  def v\n"
              + "  withCredentials([[$class: 'StringBinding', credentialsId: id, variable: 'temp']]) {\n"
              + "    v = env.temp\n"
              + "  }\n"
              + "  v\n"
              + "}\n"
              + "node {\n"
              + "  echo \"got: ${extract('" + credentialsId + "')}\"\n"
              + "}", true));

            assertThat("No fingerprint created until first use", fingerprint, nullValue());

            story.j.assertLogContains("got: " + secret, story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get()));

            fingerprint = CredentialsProvider.getFingerprintOf(credentials);

            assertThat(fingerprint, notNullValue());
            assertThat(fingerprint.getJobs(), hasItem(is(p.getFullName())));
        }
    });
}
 
Example #11
Source File: SecretBuildWrapperTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-41760")
@Test public void emptySecret() throws Exception {
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, "creds", null, Secret.fromString("")));
    FreeStyleProject p = r.createFreeStyleProject();
    p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.singletonList(new StringBinding("SECRET", "creds"))));
    p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo PASSES") : new Shell("echo PASSES"));
    r.assertLogContains("PASSES", r.buildAndAssertSuccess(p));
}
 
Example #12
Source File: SecretBuildWrapperTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-24805")
@Test public void maskingFreeStyleSecrets() throws Exception {
    String firstCredentialsId = "creds_1";
    String firstPassword = "p4$$";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    String secondCredentialsId = "creds_2";
    String secondPassword = "p4$$" + "someMoreStuff";
    StringCredentialsImpl secondCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, secondCredentialsId, "sample2", Secret.fromString(secondPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), secondCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding("PASS_1", firstCredentialsId),
            new StringBinding("PASS_2", secondCredentialsId)));

    FreeStyleProject f = r.createFreeStyleProject();

    f.setConcurrentBuild(true);
    f.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo \"$PASS_1\""));
    f.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_2%") : new Shell("echo \"$PASS_2\""));
    f.getBuildWrappersList().add(wrapper);

    r.configRoundtrip((Item)f);

    FreeStyleBuild b = r.buildAndAssertSuccess(f);
    r.assertLogNotContains(firstPassword, b);
    r.assertLogNotContains(secondPassword, b);
    r.assertLogContains("****", b);
}
 
Example #13
Source File: DollarSecretPatternFactoryTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Issue("JENKINS-24805")
@Test
public void maskingFreeStyleSecrets() throws Exception {
    String firstCredentialsId = "creds_1";
    String firstPassword = "a$build";
    StringCredentialsImpl firstCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, firstCredentialsId, "sample1", Secret.fromString(firstPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), firstCreds);

    String secondCredentialsId = "creds_2";
    String secondPassword = "a$$b";
    StringCredentialsImpl secondCreds = new StringCredentialsImpl(CredentialsScope.GLOBAL, secondCredentialsId, "sample2", Secret.fromString(secondPassword));

    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), secondCreds);

    SecretBuildWrapper wrapper = new SecretBuildWrapper(Arrays.asList(new StringBinding("PASS_1", firstCredentialsId),
            new StringBinding("PASS_2", secondCredentialsId)));

    FreeStyleProject project = r.createFreeStyleProject();

    project.setConcurrentBuild(true);
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_1%") : new Shell("echo \"$PASS_1\""));
    project.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %PASS_2%") : new Shell("echo \"$PASS_2\""));
    project.getBuildersList().add(new Maven("$PASS_1 $PASS_2", "default"));
    project.getBuildWrappersList().add(wrapper);

    r.configRoundtrip((Item)project);

    QueueTaskFuture<FreeStyleBuild> future = project.scheduleBuild2(0);
    FreeStyleBuild build = future.get();
    r.assertLogNotContains(firstPassword, build);
    r.assertLogNotContains(firstPassword.replace("$", "$$"), build);
    r.assertLogNotContains(secondPassword, build);
    r.assertLogNotContains(secondPassword.replace("$", "$$"), build);
    r.assertLogContains("****", build);
}
 
Example #14
Source File: GitLabRule.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
public GitLabConnectionProperty createGitLabConnectionProperty() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(getApiToken())));
        }
    }

    GitLabConnectionConfig config = Jenkins.getInstance().getDescriptorByType(GitLabConnectionConfig.class);
    GitLabConnection connection = new GitLabConnection("test", url, API_TOKEN_ID, new V3GitLabClientBuilder(), true,10, 10);
    config.addConnection(connection);
    config.save();
    return new GitLabConnectionProperty(connection.getName());
}
 
Example #15
Source File: GitLabConnectionConfigTest.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Before
public void setup() throws IOException {
    gitLabUrl = "http://localhost:" + mockServer.getPort() + "/gitlab";
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
        }
    }
}
 
Example #16
Source File: TestUtility.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
static void setupGitLabConnections(JenkinsRule jenkins, MockServerRule mockServer) throws IOException {
    GitLabConnectionConfig connectionConfig = jenkins.get(GitLabConnectionConfig.class);
    String apiTokenId = "apiTokenId";
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, apiTokenId, "GitLab API Token", Secret.fromString(TestUtility.API_TOKEN)));
        }
    }
    connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V3, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V3GitLabClientBuilder(), false, 10, 10));
    connectionConfig.addConnection(new GitLabConnection(TestUtility.GITLAB_CONNECTION_V4, "http://localhost:" + mockServer.getPort() + "/gitlab", apiTokenId, new V4GitLabClientBuilder(), false, 10, 10));

}
 
Example #17
Source File: TestUtility.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
static void addGitLabApiToken() throws IOException {
    for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
            List<Domain> domains = credentialsStore.getDomains();
            credentialsStore.addCredentials(domains.get(0),
                new StringCredentialsImpl(CredentialsScope.SYSTEM, API_TOKEN_ID, "GitLab API Token", Secret.fromString(API_TOKEN)));
        }
    }
}
 
Example #18
Source File: KubernetesTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Test
@LocalData()
public void upgradeFrom_1_1() throws Exception {
    List<Credentials> credentials = SystemCredentialsProvider.getInstance().getCredentials();
    assertEquals(3, credentials.size());
    UsernamePasswordCredentialsImpl cred0 = (UsernamePasswordCredentialsImpl) credentials.get(0);
    assertEquals("token", cred0.getId());
    assertEquals("myusername", cred0.getUsername());
    FileSystemServiceAccountCredential cred1 = (FileSystemServiceAccountCredential) credentials.get(1);
    StringCredentialsImpl cred2 = (StringCredentialsImpl) credentials.get(2);
    assertEquals("mytoken", Secret.toString(cred2.getSecret()));
    assertThat(cloud.getLabels(), hasEntry("jenkins", "slave"));
    assertEquals(cloud.DEFAULT_WAIT_FOR_POD_SEC, cloud.getWaitForPodSec());
}
 
Example #19
Source File: KubernetesCloud.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Initializer(before = InitMilestone.PLUGINS_STARTED)
public static void addAliases() {
    Jenkins.XSTREAM2.addCompatibilityAlias(
            "org.csanchez.jenkins.plugins.kubernetes.OpenShiftBearerTokenCredentialImpl",
            org.jenkinsci.plugins.kubernetes.credentials.OpenShiftBearerTokenCredentialImpl.class);
    Jenkins.XSTREAM2.addCompatibilityAlias(
            "org.csanchez.jenkins.plugins.kubernetes.OpenShiftTokenCredentialImpl",
            StringCredentialsImpl.class);
    Jenkins.XSTREAM2.addCompatibilityAlias("org.csanchez.jenkins.plugins.kubernetes.ServiceAccountCredential",
            org.jenkinsci.plugins.kubernetes.credentials.FileSystemServiceAccountCredential.class);
}
 
Example #20
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #21
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
}
 
Example #22
Source File: SecretRetrieverTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
private void setupCredentials(String credentialId, String secret) throws Exception {
    final CredentialsStore credentialsStore =
            CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
    final Domain domain = Domain.global();
    final Credentials credentials =
            new StringCredentialsImpl(
                    CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
    credentialsStore.addCredentials(domain, credentials);
}
 
Example #23
Source File: JiraCloudSiteConfigDescriptorTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
private void setupCredentials(String credentialId, String secret) throws Exception {
    final CredentialsStore credentialsStore =
            CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
    final Domain domain = Domain.global();
    final Credentials credentials =
            new StringCredentialsImpl(
                    CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
    credentialsStore.addCredentials(domain, credentials);
}
 
Example #24
Source File: CredentialsTestUtil.java    From credentials-binding-plugin with MIT License 4 votes vote down vote up
/**
 * Registers the given value as a {@link StringCredentials} into the default {@link CredentialsProvider} using the
 * specified credentials id.
 */
public static void setStringCredentials(ModelObject context, String credentialsId, String value) throws IOException {
    StringCredentials creds = new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, null, Secret.fromString(value));
    CredentialsProvider.lookupStores(context).iterator().next().addCredentials(Domain.global(), creds);
}
 
Example #25
Source File: JiraSendDeploymentInfoStepTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 4 votes vote down vote up
private static BaseStandardCredentials secretCredential() {
    return new StringCredentialsImpl(
            CredentialsScope.GLOBAL, CREDENTIAL_ID, "test-secret", Secret.fromString("secret"));
}
 
Example #26
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 4 votes vote down vote up
@Issue("JENKINS-30326")
@Test
public void testGlobalBindingWithAuthorization() {
    story.addStep(new Statement() {
        @SuppressWarnings("deprecation") // using TestExtension would be better, as would calling ScriptApproval.preapprove
        @Override public void evaluate() throws Throwable {
            // configure security
            story.j.jenkins.setSecurityRealm(story.j.createDummySecurityRealm());
            story.j.jenkins.setAuthorizationStrategy(new FullControlOnceLoggedInAuthorizationStrategy());
            // create the user.
            User.get("dummy", true);
            
            // enable the run as user strategy for the AuthorizeProject plugin
            Map<String, Boolean> strategies = new HashMap<String, Boolean>();
            strategies.put(story.j.jenkins.getDescriptor(SpecificUsersAuthorizationStrategy.class).getId(), true);
            QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(new ProjectQueueItemAuthenticator(strategies));

            // blanket whitelist all methods (easier than whitelisting Jenkins.getAuthentication)
            story.j.jenkins.getExtensionList(Whitelist.class).add(new BlanketWhitelist());

            String credentialsId = "creds";
            String secret = "s3cr3t";
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new StringCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", Secret.fromString(secret)));
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");

            p.setDefinition(new CpsFlowDefinition(""
                    + "node {\n"
                    + "  def authentication = Jenkins.getAuthentication()\n"
                    + "  echo \"running as user: $authentication.principal\"\n"
                    + "  withCredentials([string(credentialsId: '" + credentialsId + "', variable: 'SECRET')]) {\n"
                    + "    writeFile file:'test', text: \"$env.SECRET\"\n"
                    + "    def content = readFile 'test'\n"
                    + "    if (\"$content\" != \"" + secret + "\") {\n"
                    + "      error 'The credential was not bound into the workflow correctly'\n"
                    + "    }\n"
                    + "  }\n"
                    + "}", true));
            // run the job as a specific user
            SpecificUsersAuthorizationStrategy strategy = new SpecificUsersAuthorizationStrategy("dummy");
            strategy.setDontRestrictJobConfiguration(true);
            p.addProperty(new AuthorizeProjectProperty(strategy));

            // the build will fail if we can not locate the credentials
            WorkflowRun b = story.j.assertBuildStatusSuccess(p.scheduleBuild2(0).get());
            // make sure this was actually run as a user and not system
            story.j.assertLogContains("running as user: dummy", b);
        }
    });
}
 
Example #27
Source File: JiraSendBuildInfoStepTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 4 votes vote down vote up
private static BaseStandardCredentials secretCredential() {
    return new StringCredentialsImpl(
            CredentialsScope.GLOBAL, CREDENTIAL_ID, "test-secret", Secret.fromString("secret"));
}