com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl. 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: 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 #2
Source File: SiteTest.java    From jira-steps-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void test_credentials() throws Exception {
  String username = "user1";
  String password = "mypassword";
  String issueId = "ISSUE-1";
  String commentId = "1";

  UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test1", null, username, password);
  SystemCredentialsProvider.getInstance().getCredentials().add(c);

  Site site = new Site("TEST", new URL(wireMockRule.baseUrl()), LoginType.CREDENTIAL.name(), 10000);
  site.setCredentialsId(c.getId());

  String url = "/rest/api/2/issue/" + issueId + "/comment/" + commentId;
  wireMockRule.stubFor(get(url).willReturn(aResponse().withBody("{}")));
  site.getService().getComment(issueId, commentId);

  String token = Base64.getEncoder().encodeToString((username + ":" + password).getBytes());
  wireMockRule.verify(getRequestedFor(urlEqualTo(url)).withHeader("Authorization", equalTo("Basic " + token)));
}
 
Example #3
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void listAllCredentials() throws IOException {
    SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    CredentialsStore systemStore = system.getStore(j.getInstance());
    systemStore.addDomain(new Domain("domain1", null, null));
    systemStore.addDomain(new Domain("domain2", null, null));
    systemStore.addCredentials(systemStore.getDomainByName("domain1"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "admin", "pass$wd"));
    systemStore.addCredentials(systemStore.getDomainByName("domain2"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "joe", "pass$wd"));

    CredentialsStoreAction credentialsStoreAction = ExtensionList.lookup(ViewCredentialsAction.class).get(0).getStore("system");
    CredentialsStoreAction.DomainWrapper domain1 = credentialsStoreAction.getDomain("domain1");
    CredentialsStoreAction.DomainWrapper domain2 = credentialsStoreAction.getDomain("domain2");

    CredentialsStoreAction.CredentialsWrapper credentials1 = domain1.getCredentialsList().get(0);
    CredentialsStoreAction.CredentialsWrapper credentials2 = domain2.getCredentialsList().get(0);
    List<Map>  creds = get("/search?q=type:credential;organization:jenkins", List.class);
    Assert.assertEquals(2, creds.size());
    Assert.assertEquals(credentials1.getId(), creds.get(0).get("id"));
    Assert.assertEquals(credentials2.getId(), creds.get(1).get("id"));

    creds = get("/search?q=type:credential;organization:jenkins;domain:domain2", List.class);
    Assert.assertEquals(1, creds.size());
    Assert.assertEquals(credentials2.getId(), creds.get(0).get("id"));
}
 
Example #4
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void testStepWithGlobalCredentials() throws Exception {

	String globalCredentialsId = "global-aws-creds";

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(globalCredentialsId);

	StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			globalCredentialsId, "test-global-creds", "global-aws-access-key-id", "global-aws-secret-access-key");
	SystemCredentialsProvider.getInstance().getCredentials().add(key);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithGlobalCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + globalCredentialsId + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
}
 
Example #5
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 #6
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 #7
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 #8
Source File: Security1446Test.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
@Test
@Issue("SECURITY-1446")
public void testExportWithEnvVar() throws Exception {
    final String message = "Hello, world! PATH=${PATH} JAVA_HOME=^${JAVA_HOME}";
    ConfiguratorRegistry registry = ConfiguratorRegistry.get();
    ConfigurationContext context = new ConfigurationContext(registry);

    DataBoundConfigurator<UsernamePasswordCredentialsImpl> configurator = new DataBoundConfigurator<>(UsernamePasswordCredentialsImpl.class);
    UsernamePasswordCredentialsImpl creds = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "test",
            message, "foo", "bar");
    final CNode config = configurator.describe(creds, context);
    final Node valueNode = ConfigurationAsCode.get().toYaml(config);
    final String exported;
    try (StringWriter writer = new StringWriter()) {
        ConfigurationAsCode.serializeYamlNode(valueNode, writer);
        exported = writer.toString();
    } catch (IOException e) {
        throw new YAMLException(e);
    }

    assertThat("Message was not escaped", exported, not(containsString(message)));
    assertThat("Improper masking for PATH", exported, containsString("^${PATH}"));
    assertThat("Improper masking for JAVA_HOME", exported, containsString("^^${JAVA_HOME}"));
}
 
Example #9
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 #10
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 #11
Source File: SaveableChangeListenerTest.java    From audit-log-plugin with MIT License 6 votes vote down vote up
@Issue("ISSUE-35")
@Test
public void testOnCredentialsUsage() throws Exception {
    UsernamePasswordCredentialsImpl credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "secret-id", "test credentials", "bob","secret");
    CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), credentials);
    JenkinsRule.WebClient wc = j.createWebClient();
    FreeStyleProject job = j.createFreeStyleProject();
    job.addProperty(new ParametersDefinitionProperty(
            new CredentialsParameterDefinition(
                "SECRET",
                "The secret",
                "secret-id",
                Credentials.class.getName(),
                false
            )));
    job.getBuildersList().add(new CaptureEnvironmentBuilder());
    job.scheduleBuild2(0, new ParametersAction(new CredentialsParameterValue("SECRET", "secret-id", "The secret", true))).get();

    List<LogEvent> events = app.getEvents();
    assertThat(events).hasSize(4);
    assertThat(events).extracting(event -> ((AuditMessage) event.getMessage()).getId().toString()).containsSequence("createItem", "buildStart", "useCredentials", "buildFinish");
}
 
Example #12
Source File: ContainerExecDecoratorPipelineTest.java    From kubernetes-plugin with Apache License 2.0 6 votes vote down vote up
@Test
public void docker() throws Exception {
    StandardUsernamePasswordCredentials credentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
            "ContainerExecDecoratorPipelineTest-docker", "bob", "myusername", "secret_password");
    SystemCredentialsProvider.getInstance().getCredentials().add(credentials);

    containerExecLogs.capture(1000);
    assertNotNull(createJobThenScheduleRun());
    r.waitForCompletion(b);
    // docker login will fail but we can check that it runs the correct command
    r.assertLogContains("Executing command: \"docker\" \"login\" \"-u\" \"myusername\" \"-p\" ******** \"https://index.docker.io/v1/\"", b);
    // check that we don't accidentally start exporting sensitive info to the build log
    r.assertLogNotContains("secret_password", b);
    // check that we don't accidentally start exporting sensitive info to the Jenkins log
    assertFalse("credential leaked to log",
            containerExecLogs.getMessages().stream().anyMatch(msg -> msg.contains("secret_password")));
}
 
Example #13
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 #14
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 #15
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 #16
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testListCredentials() throws Exception {
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	StandardUsernamePasswordCredentials folderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			"folder-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	StandardUsernamePasswordCredentials globalCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			"global-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");

	folderStore.addCredentials(Domain.global(), folderCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(globalCredentials);
	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 #17
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 #18
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithFolderCredentials() throws Exception {

	String folderCredentialsId = "folders-aws-creds";

	// Create a folder with credentials in its store
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	StandardUsernamePasswordCredentials inFolderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
																								  folderCredentialsId, "test-folder-creds", "folder-aws-access-key-id", "folder-aws-secret-access-key");
	folderStore.addCredentials(Domain.global(), inFolderCredentials);
	SystemCredentialsProvider.getInstance().save();

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(folderCredentialsId);

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  withAWS (credentials: '" + folderCredentialsId + "') {\n"
													+ "    echo 'It works!'\n"
													+ "  }\n"
													+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

}
 
Example #19
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithBasicAndAwsGlobalCredentials() throws Exception {

	String globalBaseCreds = "global-basic-creds";
	String globalAwsCreds = "global-aws-creds";

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(globalBaseCreds);

	StandardUsernamePasswordCredentials key = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			globalBaseCreds, "test-global-creds", "global-aws-access-key-id", "global-aws-secret-access-key");

	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			globalAwsCreds, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");

	SystemCredentialsProvider.getInstance().getCredentials().add(amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(key);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = jenkinsRule.jenkins.createProject(WorkflowJob.class, "testStepWithBasicAndAwsGlobalCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + globalBaseCreds + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));
}
 
Example #20
Source File: KubectlBuildWrapperTest.java    From kubernetes-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setUp() throws Exception {
    deletePods(cloud.connect(), getLabels(cloud, this, name), false);
    assertNotNull(createJobThenScheduleRun());
    UsernamePasswordCredentialsImpl creds = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "id", "some credentials", "username", "password");
    SystemCredentialsProvider.getInstance().getCredentials().add(creds);
}
 
Example #21
Source File: GitHubSCMBuilderTest.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
@Before
public void setUp() throws IOException {
    owner = j.createProject(WorkflowMultiBranchProject.class);
    Credentials userPasswordCredential = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "user-pass", null, "git-user", "git-secret");
    Credentials sshPrivateKeyCredential = new BasicSSHUserPrivateKey(CredentialsScope.GLOBAL, "user-key", "git",
            new BasicSSHUserPrivateKey.UsersPrivateKeySource(), null, null);
    SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(),
            Arrays.asList(userPasswordCredential, sshPrivateKeyCredential)));
}
 
Example #22
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 #23
Source File: CredentialApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void listCredentials() throws IOException {
    SystemCredentialsProvider.ProviderImpl system = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    CredentialsStore systemStore = system.getStore(j.getInstance());
    systemStore.addDomain(new Domain("domain1", null, null));
    systemStore.addCredentials(systemStore.getDomainByName("domain1"), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null,null, "admin", "pass$wd"));


    CredentialsStoreAction credentialsStoreAction = ExtensionList.lookup(ViewCredentialsAction.class).get(0).getStore("system");
    CredentialsStoreAction.DomainWrapper domainWrapper = credentialsStoreAction.getDomain("domain1");
    CredentialsStoreAction.CredentialsWrapper credentialsWrapper = domainWrapper.getCredentialsList().get(0);


    List<Map>  creds = get("/organizations/jenkins/credentials/system/domains/domain1/credentials/", List.class);
    Assert.assertEquals(1, creds.size());
    Map cred = creds.get(0);
    Assert.assertNotNull(cred.get("id"));

    Map cred1 = get("/organizations/jenkins/credentials/system/domains/domain1/credentials/"+cred.get("id")+"/");

    Assert.assertEquals(credentialsWrapper.getId(),cred1.get("id"));
    Assert.assertEquals(credentialsWrapper.getTypeName(),cred1.get("typeName"));
    Assert.assertEquals(credentialsWrapper.getDisplayName(),cred1.get("displayName"));
    Assert.assertEquals(credentialsWrapper.getFullName(),cred1.get("fullName"));
    Assert.assertEquals(String.format("%s:%s:%s", credentialsWrapper.getDisplayName(), credentialsWrapper.getDomain().getUrlName(), credentialsWrapper.getTypeName()),cred1.get("description"));
    Assert.assertEquals(credentialsWrapper.getDomain().getUrlName(),cred1.get("domain"));
}
 
Example #24
Source File: GitScm.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private void createPWCredentials(String credentialId, User user, @JsonBody JSONObject request, String repositoryUrl) {

        StandardUsernamePasswordCredentials existingCredential =
            CredentialsUtils.findCredential(credentialId,
                                            StandardUsernamePasswordCredentials.class,
                                            new BlueOceanDomainRequirement());

        String requestUsername = request.getString("userName");
        String requestPassword = request.getString("password");

        // Un-normalized repositoryUrl so the description matches user input.
        String description = String.format("%s for %s", CREDENTIAL_DESCRIPTION_PW, repositoryUrl);

        final StandardUsernamePasswordCredentials newCredential =
            new UsernamePasswordCredentialsImpl(CredentialsScope.USER,
                                                credentialId,
                                                description,
                                                requestUsername,
                                                requestPassword);

        try {
            if (existingCredential == null) {
                CredentialsUtils.createCredentialsInUserStore(newCredential,
                                                              user,
                                                              CREDENTIAL_DOMAIN_NAME,
                                                              ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
            } else {
                CredentialsUtils.updateCredentialsInUserStore(existingCredential,
                                                              newCredential,
                                                              user,
                                                              CREDENTIAL_DOMAIN_NAME,
                                                              ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
            }
        } catch (IOException e) {
            throw new ServiceException.UnexpectedErrorException("Could not persist credential", e);
        }
    }
 
Example #25
Source File: AbstractBitbucketScm.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Request payload:
 * {
 *     "userName": "joe",
 *     "password":"****",
 *     "apiUrl":"mybitbucketserver.com"
 * }
 * @param request userName and password of bitbucket server
 *
 * @return credential id
 */
@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    User authenticatedUser = User.current();
    if(authenticatedUser == null){
        throw new ServiceException.UnauthorizedException("No logged in user found");
    }

    String userName = (String) request.get("userName");
    String password = (String) request.get("password");
    String apiUrl = (String) request.get("apiUrl");

    validate(userName, password, apiUrl);

    final StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER,
            createCredentialId(apiUrl), "Bitbucket server credentials", userName, password);

    //if credentials are wrong, this call will fail with 401 error
    validateCredential(apiUrl, credential);

    StandardUsernamePasswordCredentials bbCredentials = CredentialsUtils.findCredential(createCredentialId(apiUrl),
            StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());

    try {
        if (bbCredentials == null) {
            CredentialsUtils.createCredentialsInUserStore(
                    credential, authenticatedUser, getDomainId(),
                    ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
        } else {
            CredentialsUtils.updateCredentialsInUserStore(
                    bbCredentials, credential, authenticatedUser, getDomainId(),
                    ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
        }

        return createResponse(credential.getId());
    }catch (IOException e){
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
}
 
Example #26
Source File: RegistryEndpointStepTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void stepExecutionWithCredentialsAndQueueItemAuthenticator() throws Exception {
    assumeNotWindows();

    r.getInstance().setSecurityRealm(r.createDummySecurityRealm());
    MockAuthorizationStrategy auth = new MockAuthorizationStrategy()
            .grant(Jenkins.READ).everywhere().to("alice", "bob")
            .grant(Computer.BUILD).everywhere().to("alice", "bob")
            // Item.CONFIGURE implies Credentials.USE_ITEM, which is what CredentialsProvider.findCredentialById
            // uses when determining whether to include item-scope credentials in the search.
            .grant(Item.CONFIGURE).everywhere().to("alice");
    r.getInstance().setAuthorizationStrategy(auth);

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

    String script = "node {\n" +
            "  mockDockerLoginWithEcho {\n" +
            "    withDockerRegistry(url: 'https://my-reg:1234', credentialsId: 'registryCreds') {\n" +
            "    }\n" +
            "  }\n" +
            "}";
    WorkflowJob p1 = r.createProject(WorkflowJob.class, "prj1");
    p1.setDefinition(new CpsFlowDefinition(script, true));
    WorkflowJob p2 = r.createProject(WorkflowJob.class, "prj2");
    p2.setDefinition(new CpsFlowDefinition(script, true));

    Map<String, Authentication> jobsToAuths = new HashMap<>();
    jobsToAuths.put(p1.getFullName(), User.getById("alice", true).impersonate());
    jobsToAuths.put(p2.getFullName(), User.getById("bob", true).impersonate());
    QueueItemAuthenticatorConfiguration.get().getAuthenticators().replace(new MockQueueItemAuthenticator(jobsToAuths));

    // Alice has Credentials.USE_ITEM permission and should be able to use the credential.
    WorkflowRun b1 = r.buildAndAssertSuccess(p1);
    r.assertLogContains("docker login -u me -p pass https://my-reg:1234", b1);

    // Bob does not have Credentials.USE_ITEM permission and should not be able to use the credential.
    r.assertBuildStatus(Result.FAILURE, p2.scheduleBuild2(0));
}
 
Example #27
Source File: Site.java    From jira-steps-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(final @AncestorInPath Item item,
    @QueryParameter String credentialsId,
    final @QueryParameter String url) {

  StandardListBoxModel result = new StandardListBoxModel();

  credentialsId = StringUtils.trimToEmpty(credentialsId);
  if (item == null) {
    if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
      return result.includeCurrentValue(credentialsId);
    }
  } else {
    if (!item.hasPermission(Item.EXTENDED_READ) && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
      return result.includeCurrentValue(credentialsId);
    }
  }

  Authentication authentication = getAuthentication(item);
  List<DomainRequirement> domainRequirements = URIRequirementBuilder.fromUri(url).build();
  CredentialsMatcher always = CredentialsMatchers.always();
  Class<? extends StandardUsernameCredentials> type = UsernamePasswordCredentialsImpl.class;

  result.includeEmptyValue();
  if (item != null) {
    result.includeMatchingAs(authentication, item, type, domainRequirements, always);
  } else {
    result.includeMatchingAs(authentication, Jenkins.get(), type, domainRequirements, always);
  }
  return result;
}
 
Example #28
Source File: PendingChecksFilterTests.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  UsernamePasswordCredentialsImpl c =
      new UsernamePasswordCredentialsImpl(
          CredentialsScope.GLOBAL, "cid", "cid", "USERNAME", "PASSWORD");
  CredentialsProvider.lookupStores(j.jenkins)
      .iterator()
      .next()
      .addCredentials(Domain.global(), c);

  g.getClient()
      .when(
          HttpRequest.request("/a/plugins/checks/checks.pending/")
              .withQueryStringParameters(query)
              .withMethod("GET"))
      .respond(
          HttpResponse.response()
              .withStatusCode(200)
              .withBody(JsonBody.json(pendingChecksInfos)));

  GerritSCMSource source =
      new GerritSCMSource(
          String.format(
              "https://%s:%s/a/test",
              g.getClient().remoteAddress().getHostName(),
              g.getClient().remoteAddress().getPort()));
  source.setInsecureHttps(true);
  source.setCredentialsId("cid");
  request = context.newRequest(source, new StreamTaskListener());
}
 
Example #29
Source File: BindingStepTest.java    From credentials-binding-plugin with MIT License 5 votes vote down vote up
@Test public void configRoundTrip() throws Exception {
    story.addStep(new Statement() {
        @SuppressWarnings("rawtypes")
        @Override public void evaluate() throws Throwable {
            UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "creds", "sample", "bob", "s3cr3t");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
            BindingStep s = new StepConfigTester(story.j).configRoundTrip(new BindingStep(Collections.<MultiBinding>singletonList(new UsernamePasswordBinding("userpass", "creds"))));
            story.j.assertEqualDataBoundBeans(s.getBindings(), Collections.singletonList(new UsernamePasswordBinding("userpass", "creds")));
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), new FileCredentialsImpl(CredentialsScope.GLOBAL, "secrets", "sample", "secrets.zip",
                SecretBytes.fromBytes(new byte[] {0x50,0x4B,0x05,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00}))); // https://en.wikipedia.org/wiki/Zip_(file_format)#Limits
            new SnippetizerTester(story.j).assertRoundTrip(new BindingStep(Collections.<MultiBinding>singletonList(new ZipFileBinding("file", "secrets"))),
                "withCredentials([[$class: 'ZipFileBinding', credentialsId: 'secrets', variable: 'file']]) {\n    // some block\n}");
        }
    });
}
 
Example #30
Source File: UsernamePasswordMultiBindingTest.java    From credentials-binding-plugin with MIT License 5 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.<MultiBinding<?>>singletonList(new UsernamePasswordMultiBinding("userid", "pass", c.getId()))));
    if (Functions.isWindows()) {
        p.getBuildersList().add(new BatchFile("@echo off\necho %userid%/%pass% > auth.txt"));
    } else {
        p.getBuildersList().add(new Shell("set +x\necho $userid/$pass > auth.txt"));
    }
    r.configRoundtrip((Item)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(UsernamePasswordMultiBinding.class, binding.getClass());
    assertEquals("userid", ((UsernamePasswordMultiBinding) binding).getUsernameVariable());
    assertEquals("pass", ((UsernamePasswordMultiBinding) binding).getPasswordVariable());
    FreeStyleBuild b = r.buildAndAssertSuccess(p);
    r.assertLogNotContains(password, b);
    assertEquals(username + '/' + password, b.getWorkspace().child("auth.txt").readToString().trim());
    assertEquals("[pass, userid]", new TreeSet<String>(b.getSensitiveBuildVariables()).toString());
}