com.cloudbees.plugins.credentials.CredentialsScope Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsScope. 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: UsernamePasswordBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Test public void basics() throws Exception {
    String username = "bob";
    String password = "s3cr3t";
    UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "sample", username, password);
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
    FreeStyleProject p = r.createFreeStyleProject();
    p.getBuildWrappersList().add(new SecretBuildWrapper(Collections.<Binding<?>>singletonList(new UsernamePasswordBinding("AUTH", c.getId()))));
    p.getBuildersList().add(Functions.isWindows() ? new BatchFile("echo %AUTH% > auth.txt") : new Shell("echo $AUTH > auth.txt"));
    r.configRoundtrip(p);
    SecretBuildWrapper wrapper = p.getBuildWrappersList().get(SecretBuildWrapper.class);
    assertNotNull(wrapper);
    List<? extends MultiBinding<?>> bindings = wrapper.getBindings();
    assertEquals(1, bindings.size());
    MultiBinding<?> binding = bindings.get(0);
    assertEquals(c.getId(), binding.getCredentialsId());
    assertEquals(UsernamePasswordBinding.class, binding.getClass());
    assertEquals("AUTH", ((UsernamePasswordBinding) binding).getVariable());
    FreeStyleBuild b = r.buildAndAssertSuccess(p);
    r.assertLogNotContains(password, b);
    assertEquals(username + ':' + password, b.getWorkspace().child("auth.txt").readToString().trim());
    assertEquals("[AUTH]", b.getSensitiveBuildVariables().toString());
}
 
Example #2
Source File: DockerAgentTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@BeforeClass
public static void setUpAgent() throws Exception {
    s = j.createOnlineSlave();
    s.setLabelString("some-label docker");
    s.getNodeProperties().add(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("ONAGENT", "true"),
            new EnvironmentVariablesNodeProperty.Entry("WHICH_AGENT", "first")));
    s.setNumExecutors(2);

    s2 = j.createOnlineSlave();
    s2.setLabelString("other-docker");
    s2.getNodeProperties().add(new EnvironmentVariablesNodeProperty(new EnvironmentVariablesNodeProperty.Entry("ONAGENT", "true"),
            new EnvironmentVariablesNodeProperty.Entry("WHICH_AGENT", "second")));
    //setup credentials for docker registry
    CredentialsStore store = CredentialsProvider.lookupStores(j.jenkins).iterator().next();

    password = System.getProperty("docker.password");

    if(password != null) {
        UsernamePasswordCredentialsImpl globalCred =
                new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
                        "dockerhub", "real", "jtaboada", password);

        store.addCredentials(Domain.global(), globalCred);

    }
}
 
Example #3
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 #4
Source File: InfluxDbNotifierTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
@Test
public void testBasicAuth() {
    UsernamePasswordCredentials credentials
            = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
                    influxDbCredentialsId,
                    "Description",
                    influxDbUser,
                    influxDbPassword);
    when(config.getCredentials())
            .thenReturn(credentials);

    InfluxDbNotifier instance = new InfluxDbNotifier(config);
    assertEquals("http://fake/write?db=mockdb",
            instance.influxDbUrlString);
    assertEquals(new String(Base64.getDecoder().decode(instance.authorization)),
            "mock-user:mock-password");
}
 
Example #5
Source File: KeystoreCredentialsImpl.java    From jenkins-android-signing with Apache License 2.0 6 votes vote down vote up
@DataBoundConstructor
public KeystoreCredentialsImpl(@CheckForNull CredentialsScope scope, @CheckForNull String id, @CheckForNull String description, @Nonnull FileItem file, @CheckForNull String fileName, @CheckForNull String data, @CheckForNull String passphrase) throws IOException {
    super(scope, id, description);
    String name = file.getName();
    if (name.length() > 0) {
        this.fileName = name.replaceFirst("^.+[/\\\\]", "");
        byte[] unencrypted = file.get();
        try {
            this.data = KEY.encrypt().doFinal(unencrypted);
        } catch (GeneralSecurityException x) {
            throw new IOException2(x);
        }
    } else {
        this.fileName = fileName;
        this.data = Base64.decodeBase64(data);
    }
    this.passphrase = Secret.fromString(passphrase);
}
 
Example #6
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 #7
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-42999")
@Test
public void widerRequiredContext() throws Exception {
    final String credentialsId = "creds";
    final String credsFile = "credsFile";
    final String credsContent = "s3cr3t";
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            FileCredentialsImpl c = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "sample", credsFile, SecretBytes.fromBytes(credsContent.getBytes()));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "p");
            p.setDefinition(new CpsFlowDefinition(""
                    + "withCredentials([file(variable: 'targetFile', credentialsId: '" + credentialsId + "')]) {\n"
                    + "  echo 'We should fail before getting here'\n"
                    + "}", true));
            WorkflowRun b = story.j.assertBuildStatus(Result.FAILURE, p.scheduleBuild2(0));
            story.j.assertLogNotContains("We should fail before getting here", b);
            story.j.assertLogContains("Required context class hudson.FilePath is missing", b);
            story.j.assertLogContains("Perhaps you forgot to surround the code with a step that provides this, such as: node", b);
        }
    });
}
 
Example #8
Source File: GitHubAppCredentials.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@POST
@SuppressWarnings("unused") // stapler
@Restricted(NoExternalUse.class) // stapler
public FormValidation doTestConnection(
        @QueryParameter("appID") final String appID,
        @QueryParameter("privateKey") final String privateKey,
        @QueryParameter("apiUri") final String apiUri,
        @QueryParameter("owner") final String owner

) {
    GitHubAppCredentials gitHubAppCredential = new GitHubAppCredentials(
            CredentialsScope.GLOBAL, "test-id-not-being-saved", null,
            appID, Secret.fromString(privateKey)
    );
    gitHubAppCredential.setApiUri(apiUri);
    gitHubAppCredential.setOwner(owner);

    try {
        GitHub connect = Connector.connect(apiUri, gitHubAppCredential);
        return FormValidation.ok("Success, Remaining rate limit: " + connect.getRateLimit().getRemaining());
    } catch (Exception e) {
        return FormValidation.error(e, String.format(ERROR_AUTHENTICATING_GITHUB_APP, appID));
    }
}
 
Example #9
Source File: DockerRule.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
public DockerServerCredentials getDockerServerCredentials() throws IOException {
    final LocalDirectorySSLConfig sslContext = (LocalDirectorySSLConfig) clientConfig.getSSLConfig();

    assertThat("DockerCli must be connected via SSL", sslContext, notNullValue());

    String certPath = sslContext.getDockerCertPath();

    final String keypem = FileUtils.readFileToString(new File(certPath + "/" + "key.pem"));
    final String certpem = FileUtils.readFileToString(new File(certPath + "/" + "cert.pem"));
    final String capem = FileUtils.readFileToString(new File(certPath + "/" + "ca.pem"));

    return new DockerServerCredentials(
            CredentialsScope.GLOBAL, // scope
            null, // name
            null, //desc
            keypem,
            certpem,
            capem
    );
}
 
Example #10
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException 
 */
@Test
public void testDoFillCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);
    
    ListBoxModel model = instance.doFillCredentialsIdItems(testCredentials);
    
    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example #11
Source File: RegistryEndpointStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test
public void stepExecutionWithCredentials() throws Exception {
    assumeNotWindows();

    IdCredentials registryCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "registryCreds", null, "me", "pass");
    CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), registryCredentials);

    WorkflowJob p = r.createProject(WorkflowJob.class, "prj");
    p.setDefinition(new CpsFlowDefinition(
            "node {\n" +
                    "  mockDockerLoginWithEcho {\n" +
                    "    withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
                    "    }\n" +
                    "  }\n" +
                    "}", true));
    WorkflowRun b = r.buildAndAssertSuccess(p);
    r.assertLogContains("docker login -u me -p pass https://my-reg:1234", r.assertBuildStatusSuccess(r.waitForCompletion(b)));
}
 
Example #12
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 #13
Source File: GitLabConnection.java    From gitlab-plugin with GNU General Public License v2.0 6 votes vote down vote up
@Initializer(after = InitMilestone.PLUGINS_STARTED)
public static void migrate() throws IOException {
    GitLabConnectionConfig descriptor = (GitLabConnectionConfig) Jenkins.get().getDescriptor(GitLabConnectionConfig.class);
    if (descriptor == null) return;
    for (GitLabConnection connection : descriptor.getConnections()) {
        if (connection.apiTokenId == null && connection.apiToken != null) {
            for (CredentialsStore credentialsStore : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
                if (credentialsStore instanceof SystemCredentialsProvider.StoreImpl) {
                    List<Domain> domains = credentialsStore.getDomains();
                    connection.apiTokenId = UUID.randomUUID().toString();
                    credentialsStore.addCredentials(domains.get(0),
                        new GitLabApiTokenImpl(CredentialsScope.SYSTEM, connection.apiTokenId, "GitLab API Token", Secret.fromString(connection.apiToken)));
                }
            }
        }
    }
    descriptor.save();
}
 
Example #14
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 #15
Source File: S3UploadStepIntegrationTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Issue("JENKINS-49025")
@Test
public void smokes() throws Exception {
	String globalCredentialsId = "x";
	StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, globalCredentialsId, "x", "x", "x");
	SystemCredentialsProvider.getInstance().getCredentials().add(key);
	WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
	p.setDefinition(new CpsFlowDefinition(
			"node('" + r.createSlave().getNodeName() + "') {\n" +
					"  withAWS (credentials: '" + globalCredentialsId + "') {\n" +
					"    writeFile file: 'x', text: ''\n" +
					"    try {\n" +
					"      s3Upload bucket: 'x', file: 'x', path: 'x'\n" +
					"      fail 'should not have worked'\n" +
					"    } catch (com.amazonaws.services.s3.model.AmazonS3Exception x) {\n" +
					"      echo(/got $x as expected/)\n" +
					"    }\n" +
					"  }\n" +
					"}\n", true)
	);
	r.assertBuildStatusSuccess(p.scheduleBuild2(0));
}
 
Example #16
Source File: IntegrationTest.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
@SuppressWarnings({"PMD.AvoidCatchingThrowable", "IllegalCatch"})
protected DumbSlave createDockerContainerAgent(final DockerContainer dockerContainer) {
    try {
        SystemCredentialsProvider.getInstance().getDomainCredentialsMap().put(Domain.global(),
                Collections.singletonList(
                        new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM, "dummyCredentialId",
                                null, "test", "test")
                )
        );
        DumbSlave agent = new DumbSlave("docker", "/home/test",
                new SSHLauncher(dockerContainer.ipBound(22), dockerContainer.port(22), "dummyCredentialId"));
        agent.setNodeProperties(Collections.singletonList(new EnvironmentVariablesNodeProperty(
                new Entry("JAVA_HOME", "/usr/lib/jvm/java-8-openjdk-amd64/jre"))));
        getJenkins().jenkins.addNode(agent);
        getJenkins().waitOnline(agent);

        return agent;
    }
    catch (Throwable e) {
        throw new AssumptionViolatedException("Failed to create docker container", e);
    }
}
 
Example #17
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 #18
Source File: BuildStatusConfigTest.java    From github-autostatus-plugin with MIT License 6 votes vote down vote up
/**
 * Verifies doFillCredentialsIdItems adds values from the credentials store
 * @throws IOException
 */
@Test
public void testDoFillHttpCredentialsIdItemsAddsFromCredentialsStore() throws IOException {
    StandardUsernameCredentials user = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, testCredentials, "Description", testCredentialsUser, testCredentialsPassword);
    CredentialsProvider.lookupStores(j.getInstance()).iterator().next().addCredentials(Domain.global(), user);

    BuildStatusConfig instance = new BuildStatusConfig();
    instance.setCredentialsId(testCredentials);

    ListBoxModel model = instance.doFillHttpCredentialsIdItems(testCredentials);

    assertEquals(2, model.size());
    ListBoxModel.Option item1 = model.get(0);
    assertEquals("", item1.value);
    assertEquals("- none -", item1.name);

    ListBoxModel.Option item2 = model.get(1);
    assertEquals(testCredentials, item2.value);
}
 
Example #19
Source File: ServerEndpointStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void stepExecutionWithCredentials() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            assumeNotWindows();
            IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, "prj");
            p.setDefinition(new CpsFlowDefinition(
                    "node {\n" +
                            "  withDockerServer(server: [uri: 'tcp://host:1234', credentialsId: 'serverCreds']) {\n" +
                            "    sh 'echo would be connecting to $DOCKER_HOST'\n" +
                            "    sh 'echo DOCKER_TLS_VERIFY=$DOCKER_TLS_VERIFY'\n" +
                            "    sh 'echo DOCKER_CERT_PATH=$DOCKER_CERT_PATH is not empty'\n" +
                            "  }\n" +
                            "}", true));
            WorkflowRun b = story.j.buildAndAssertSuccess(p);
            story.j.assertLogContains("would be connecting to tcp://host:1234", b);
            story.j.assertLogContains("DOCKER_TLS_VERIFY=1", b);
            story.j.assertLogNotContains("DOCKER_CERT_PATH= is not empty", b);
        }
    });
}
 
Example #20
Source File: ServerEndpointStepTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test public void configRoundTrip() {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            IdCredentials serverCredentials = new DockerServerCredentials(CredentialsScope.GLOBAL, "serverCreds", null, "clientKey", "clientCertificate", "serverCaCertificate");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), serverCredentials);
            StepConfigTester sct = new StepConfigTester(story.j);
            Map<String,Object> serverConfig = new TreeMap<String,Object>();
            serverConfig.put("uri", "tcp://host:2375");
            serverConfig.put("credentialsId", serverCredentials.getId());
            Map<String,Object> config = Collections.<String,Object>singletonMap("server", serverConfig);
            ServerEndpointStep step = DescribableHelper.instantiate(ServerEndpointStep.class, config);
            step = sct.configRoundTrip(step);
            DockerServerEndpoint server = step.getServer();
            assertNotNull(server);
            assertEquals("tcp://host:2375", server.getUri());
            assertEquals(serverCredentials.getId(), server.getCredentialsId());
            assertEquals(config, DescribableHelper.uninstantiate(step));
       }
    });
}
 
Example #21
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 #22
Source File: VaultAppRoleCredential.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@DataBoundConstructor
public VaultAppRoleCredential(@CheckForNull CredentialsScope scope, @CheckForNull String id,
    @CheckForNull String description, @NonNull String roleId, @NonNull Secret secretId,
    String path) {
    super(scope, id, description);
    this.secretId = secretId;
    this.roleId = roleId;
    if (path == null) {
        this.path = "approle";
    } else {
        this.path = path;
    }
}
 
Example #23
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 #24
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testListAWSCredentials() throws Exception {

	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			"test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	AmazonWebServicesCredentials globalAmazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			"global-test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");

	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(globalAmazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	final WithAWSStep.DescriptorImpl descriptor = jenkinsRule.jenkins.getDescriptorByType(WithAWSStep.DescriptorImpl.class);

	// 3 options: Root credentials, folder credentials and "none"
	ListBoxModel list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());

	StandardUsernamePasswordCredentials systemCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
			"system-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	SystemCredentialsProvider.getInstance().getCredentials().add(systemCredentials);

	// Still 3 options: Root credentials, folder credentials and "none"
	list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());
}
 
Example #25
Source File: VaultGCPCredential.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@DataBoundConstructor
public VaultGCPCredential(@CheckForNull CredentialsScope scope, @CheckForNull String id,
    @CheckForNull String description, @NonNull String role, @NonNull String audience) {
    super(scope, id, description);
    this.role = role;
    this.audience = audience;
}
 
Example #26
Source File: VaultTokenCredentialBindingIT.java    From hashicorp-vault-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldUseDefaultsIfVariablesAreOmitted() {
    final String credentialsId = "creds";
    final String vaultAddr = "https://localhost:8200";
    final String token = "fakeToken";
    final String jobId = "testJob";
    story.addStep(new Statement() {
        @Override
        public void evaluate() throws Throwable {
            VaultTokenCredential c = new VaultTokenCredential(CredentialsScope.GLOBAL,
                credentialsId, "fake description", Secret.fromString(token));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next()
                .addCredentials(Domain.global(), c);
            WorkflowJob p = story.j.jenkins.createProject(WorkflowJob.class, jobId);
            p.setDefinition(new CpsFlowDefinition(""
                + "node {\n"
                + "  withCredentials([[$class: 'VaultTokenCredentialBinding', credentialsId: '"
                + credentialsId + "', vaultAddr: '" + vaultAddr + "']]) {\n"
                + "      " + getShellString() + " 'echo " + getVariable("VAULT_ADDR") + ":"
                + getVariable("VAULT_TOKEN") + " > script'\n"
                + "  }\n"
                + "}", true));
            WorkflowRun b = p.scheduleBuild2(0).waitForStart();
            story.j.assertBuildStatus(Result.SUCCESS, story.j.waitForCompletion(b));
            story.j.assertLogNotContains(token, b);
            FilePath script = story.j.jenkins.getWorkspaceFor(p).child("script");
            assertEquals(vaultAddr + ":" + token, script.readToString().trim());
        }
    });
}
 
Example #27
Source File: RealEc2ApiIntegrationTest.java    From ec2-spot-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Related to https://github.com/jenkinsci/ec2-fleet-plugin/issues/60
 *
 * @throws Exception e
 */
@Test
public void shouldSuccessfullyUpdateBigFleetPluginWithFleetStatus() throws Exception {
    final int targetCapacity = 30;

    final AWSCredentials awsCredentials = getAwsCredentials();

    SystemCredentialsProvider.getInstance().getCredentials().add(
            new AWSCredentialsImpl(CredentialsScope.SYSTEM, "credId",
                    awsCredentials.getAWSAccessKeyId(), awsCredentials.getAWSSecretKey(), "d"));

    withFleet(awsCredentials, targetCapacity, new WithFleetBody() {
        @Override
        public void run(AmazonEC2 amazonEC2, String fleetId) throws Exception {
            EC2FleetCloud cloud = new EC2FleetCloud(null, null, "credId", null, null, null, fleetId,
                    null, null, null, false, false,
                    0, 0, 0, 0, false, false,
                    false, 0, 0, false, 10, false);
            j.jenkins.clouds.add(cloud);

            final long start = System.currentTimeMillis();
            final long max = TimeUnit.MINUTES.toMillis(2);
            while (System.currentTimeMillis() - start < max) {
                // if (cloud.getStatusCache().getNumActive() >= targetCapacity) break;
                Thread.sleep(TimeUnit.SECONDS.toMillis(10));
            }

            // todo replace with proper accessor assertEquals(targetCapacity, cloud.getStatusCache().getNumActive());
            // assertEquals(fleetId, cloud.getStatusCache().getFleetId());
        }
    });
}
 
Example #28
Source File: CredentialsHelper.java    From violation-comments-to-stash-plugin with MIT License 5 votes vote down vote up
public static String migrateCredentials(final String username, final String password) {
  String credentialsId = null;
  final DomainRequirement domainRequirement = null;
  final List<StandardUsernamePasswordCredentials> credentials =
      CredentialsMatchers.filter(
          CredentialsProvider.lookupCredentials(
              StandardUsernamePasswordCredentials.class,
              Jenkins.getInstance(),
              ACL.SYSTEM,
              domainRequirement),
          CredentialsMatchers.withUsername(username));
  for (final StandardUsernamePasswordCredentials cred : credentials) {
    if (StringUtils.equals(password, Secret.toString(cred.getPassword()))) {
      // If some credentials have the same username/password, use those.
      credentialsId = cred.getId();
      break;
    }
  }
  if (StringUtils.isBlank(credentialsId)) {
    // If we couldn't find any existing credentials,
    // create new credentials with the principal and secret and use it.
    final StandardUsernamePasswordCredentials newCredentials =
        new UsernamePasswordCredentialsImpl(
            CredentialsScope.SYSTEM,
            null,
            "Migrated by Violation comments to bitbucket plugin",
            username,
            password);
    SystemCredentialsProvider.getInstance().getCredentials().add(newCredentials);
    credentialsId = newCredentials.getId();
  }
  if (StringUtils.isNotEmpty(credentialsId)) {
    return credentialsId;
  } else {
    return null;
  }
}
 
Example #29
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCommitMustFail() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(null);

    Credentials dummy = new DummyCredentials(CredentialsScope.GLOBAL, "user", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(dummy);

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_COMMIT, b1);
}
 
Example #30
Source File: UserSSHKeyManager.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the existing generated SSH key for the user or creates one and
 * returns it in the user's credential store
 * @param user owner of the key
 * @return the user's personal private key
 */
public static @Nonnull BasicSSHUserPrivateKey getOrCreate(@Nonnull User user) {
    Preconditions.checkNotNull(user);

    CredentialsStore store = getUserStore(user);
    if(store == null){
        throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
    }
    // try to find the right key
    for (Credentials cred : store.getCredentials(getDomain(store))) {
        if (cred instanceof BasicSSHUserPrivateKey) {
            BasicSSHUserPrivateKey sshKey = (BasicSSHUserPrivateKey)cred;
            if (BLUEOCEAN_GENERATED_SSH_KEY_ID.equals(sshKey.getId())) {
                return sshKey;
            }
        }
    }
    // if none found, create one
    try {
        // create one!
        String privateKey = SSHKeyUtils.generateKey(KEY_SIZE).trim();
        BasicSSHUserPrivateKey.DirectEntryPrivateKeySource keySource = new BasicSSHUserPrivateKey.DirectEntryPrivateKeySource(privateKey);
        BasicSSHUserPrivateKey key = new BasicSSHUserPrivateKey(CredentialsScope.USER, BLUEOCEAN_GENERATED_SSH_KEY_ID, user.getId(), keySource, null, BLUEOCEAN_GENERATED_SSH_KEY_ID);
        store.addCredentials(getDomain(store), key);
        store.save();
        return key;
    } catch (IOException ex) {
        throw new ServiceException.UnexpectedErrorException("Failed to create the private key", ex);
    }
}