Java Code Examples for com.cloudbees.plugins.credentials.CredentialsProvider

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsProvider. These examples are extracted from open source projects. 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 Project: credentials-binding-plugin   Source File: BindingStepTest.java    License: 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 2
Source Project: credentials-binding-plugin   Source File: ZipFileBindingTest.java    License: MIT License 6 votes vote down vote up
@Issue("JENKINS-30941")
@Test
public void cleanUpSucceeds() throws Exception {
    /** Issue was just present on Linux not windows - but the test will run on both */

    final String credentialsId = "zipfile";

    FileCredentialsImpl fc = new FileCredentialsImpl(CredentialsScope.GLOBAL, credentialsId, "Just a zip file", "a.zip", SecretBytes.fromBytes(IOUtils.toByteArray(ZipFileBindingTest.class.getResource("a.zip"))));
    CredentialsProvider.lookupStores(j.jenkins).iterator().next().addCredentials(Domain.global(), fc);

    final String contents = "Test of ZipFileBinding\n";
    
    WorkflowJob p = j.jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(""
                                          + "node {\n"
                                          + "  withCredentials([[$class: 'ZipFileBinding', credentialsId: '"+ credentialsId +"', variable: 'ziploc']]) {\n"
                                          + "    echo readFile(encoding: 'UTF-8', file: \"${env.ziploc}/dir/testfile.txt\")\n"
                                          + "  }\n"
                                          + "}\n"
                                          , true));

    WorkflowRun run = p.scheduleBuild2(0).get();
    j.assertBuildStatusSuccess(run);
    j.assertLogContains(contents, run);
}
 
Example 3
Source Project: credentials-binding-plugin   Source File: ZipFileBinding.java    License: MIT License 6 votes vote down vote up
public FormValidation doCheckCredentialsId(@AncestorInPath Item owner, @QueryParameter String value) {
    for (FileCredentials c : CredentialsProvider.lookupCredentials(FileCredentials.class, owner, null, Collections.<DomainRequirement>emptyList())) {
        if (c.getId().equals(value)) {
            InputStream is = null;
            try {
                is = c.getContent();
                byte[] data = new byte[4];
                if (is.read(data) == 4 && data[0] == 'P' && data[1] == 'K' && data[2] == 3 && data[3] == 4) {
                    return FormValidation.ok();
                } else {
                    return FormValidation.error(Messages.ZipFileBinding_NotZipFile());
                }
            } catch (IOException x) {
                return FormValidation.warning(Messages.ZipFileBinding_CouldNotVerifyFileFormat());
            }
            finally {
                if (is != null) {
                    IOUtils.closeQuietly(is);
                }
            }
        }
    }
    return FormValidation.error(Messages.ZipFileBinding_NoSuchCredentials());
}
 
Example 4
Source Project: docker-workflow-plugin   Source File: RegistryEndpointStepTest.java    License: 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 5
public AbstractIdCredentialsListBoxModel<?, ?> doFillCredentialIdItems(
        @AncestorInPath Item owner) {
    if (owner == null || !owner.hasPermission(Item.CONFIGURE)) {
        return new AWSCredentialsListBoxModel();
    }

    List<AmazonWebServicesCredentials>
            creds =
            CredentialsProvider
                    .lookupCredentials(AmazonWebServicesCredentials.class, owner, ACL.SYSTEM,
                            Collections.<DomainRequirement>emptyList());

    return new AWSCredentialsListBoxModel()
            .withEmptySelection()
            .withAll(creds);
}
 
Example 6
protected Void run() throws Exception {
    FilePath ws = getContext().get(FilePath.class);
    TaskListener listener = this.getContext().get(TaskListener.class);
    EnvVars envVars = getContext().get(EnvVars.class);
    WorkflowJob job = getContext().get(WorkflowJob.class);
    GitOperations gitOperations = new GitOperations(ws, listener, envVars, url);
    StandardCredentials c = CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    job,
                    Tasks.getAuthenticationOf((Queue.Task) job)),
            CredentialsMatchers.withId(credentialId));

    gitOperations.setUsernameAndPasswordCredential((StandardUsernameCredentials) c);
    gitOperations.setCurrentBranch(branch);
    gitOperations.push(true);
    return null;
}
 
Example 7
Source Project: blueocean-plugin   Source File: CredentialApiTest.java    License: MIT License 6 votes vote down vote up
@Test
public void createUsingUsernamePassword() 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));

    Map<String, Object> resp = post("/organizations/jenkins/credentials/system/domains/domain1/credentials/",
            ImmutableMap.of("credentials",
                    new ImmutableMap.Builder<String,Object>()
                            .put("password", "abcd")
                            .put("stapler-class", "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl")
                            .put("scope", "GLOBAL")
                            .put("description", "joe desc")
                            .put("$class", "com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl")
                            .put("username", "joe").build()
            )
            , 201);
    Assert.assertEquals("Username with password", resp.get("typeName"));
    Assert.assertEquals("domain1", resp.get("domain"));
}
 
Example 8
public GerritApiBuilder stepContext(StepContext context)
    throws URISyntaxException, IOException, InterruptedException {
  EnvVars envVars = context.get(EnvVars.class);
  logger(context.get(TaskListener.class).getLogger());
  if (StringUtils.isNotEmpty(envVars.get("GERRIT_API_URL"))) {
    gerritApiUrl(envVars.get("GERRIT_API_URL"));
  } else if (StringUtils.isNotEmpty(envVars.get("GERRIT_CHANGE_URL"))) {
    gerritApiUrl(new GerritURI(new URIish(envVars.get("GERRIT_CHANGE_URL"))).getApiURI());
  }
  insecureHttps(Boolean.parseBoolean(envVars.get("GERRIT_API_INSECURE_HTTPS")));
  String credentialsId = StringUtils.defaultIfEmpty(envVars.get("GERRIT_CREDENTIALS_ID"), null);
  if (credentialsId != null) {
    credentials(
        CredentialsProvider.findCredentialById(
            credentialsId, StandardUsernamePasswordCredentials.class, context.get(Run.class)));
  }
  return this;
}
 
Example 9
Source Project: github-branch-source-plugin   Source File: Connector.java    License: MIT License 6 votes vote down vote up
/**
 * Resolves the specified scan credentials in the specified context for use against the specified API endpoint.
 *
 * @param context           the context.
 * @param apiUri            the API endpoint.
 * @param scanCredentialsId the credentials to resolve.
 * @return the {@link StandardCredentials} or {@code null}
 */
@CheckForNull
public static StandardCredentials lookupScanCredentials(@CheckForNull Item context,
                                                        @CheckForNull String apiUri,
                                                        @CheckForNull String scanCredentialsId) {
    if (Util.fixEmpty(scanCredentialsId) == null) {
        return null;
    } else {
        return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                StandardUsernameCredentials.class,
                context,
                context instanceof Queue.Task
                        ? ((Queue.Task) context).getDefaultAuthentication()
                        : ACL.SYSTEM,
                githubDomainRequirements(apiUri)
            ),
            CredentialsMatchers.allOf(CredentialsMatchers.withId(scanCredentialsId), githubScanCredentialsMatcher())
        );
    }
}
 
Example 10
Source Project: remoting-kafka-plugin   Source File: GlobalKafkaConfiguration.java    License: MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillKubernetesCredentialsIdItems() {
    Jenkins.get().checkPermission(Jenkins.ADMINISTER);
    return new StandardListBoxModel().withEmptySelection()
            .withMatching(
                    CredentialsMatchers.anyOf(
                            CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                            CredentialsMatchers.instanceOf(FileCredentials.class),
                            CredentialsMatchers.instanceOf(TokenProducer.class),
                            CredentialsMatchers.instanceOf(StandardCertificateCredentials.class),
                            CredentialsMatchers.instanceOf(StringCredentials.class)),
                    CredentialsProvider.lookupCredentials(StandardCredentials.class,
                            Jenkins.get(),
                            ACL.SYSTEM,
                            Collections.EMPTY_LIST
                    ));
}
 
Example 11
Source Project: hashicorp-vault-plugin   Source File: VaultStringCredentialIT.java    License: MIT License 6 votes vote down vote up
@Test
public void shouldFailIfMissingCredentials() throws Exception {
    final String credentialsId = "cid1";
    VaultStringCredentialImpl c = new VaultStringCredentialImpl(
        null, credentialsId, "Test Credentials");
    c.setEngineVersion(1);
    CredentialsProvider.lookupStores(jenkins).iterator().next()
        .addCredentials(Domain.global(), c);
    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "testJob");
    p.setDefinition(new CpsFlowDefinition(""
        + "node {\n"
        + " withCredentials([[$class: 'VaultStringCredentialBinding', credentialsId: '"
        + credentialsId
        + "', variable: 'SECRET']]) { "
        + "      " + getShellString() + " 'echo " + getVariable("SECRET") + "'\n"
        + "  }\n"
        + "}", true));
    WorkflowRun b = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b));
    jenkins.assertLogContains("Exception", b);
}
 
Example 12
Source Project: credentials-binding-plugin   Source File: BindingStepTest.java    License: 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 13
Source Project: hashicorp-vault-plugin   Source File: VaultBuildWrapper.java    License: MIT License 6 votes vote down vote up
protected VaultCredential retrieveVaultCredentials(Run build) {
    String id = getConfiguration().getVaultCredentialId();
    if (StringUtils.isBlank(id)) {
        throw new VaultPluginException(
            "The credential id was not configured - please specify the credentials to use.");
    }
    List<VaultCredential> credentials = CredentialsProvider
        .lookupCredentials(VaultCredential.class, build.getParent(), ACL.SYSTEM,
            Collections.emptyList());
    VaultCredential credential = CredentialsMatchers
        .firstOrNull(credentials, new IdMatcher(id));

    if (credential == null) {
        throw new CredentialsUnavailableException(id);
    }

    return credential;
}
 
Example 14
Source Project: gitea-plugin   Source File: GiteaServer.java    License: MIT License 6 votes vote down vote up
/**
 * Looks up the {@link StandardCredentials} to use for auto-management of hooks.
 *
 * @return the credentials or {@code null}.
 */
@CheckForNull
public StandardCredentials credentials() {
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardCredentials.class,
                    Jenkins.get(),
                    ACL.SYSTEM,
                    URIRequirementBuilder.fromUri(serverUrl).build()
            ),
            CredentialsMatchers.allOf(
                    AuthenticationTokens.matcher(GiteaAuth.class),
                    CredentialsMatchers.withId(credentialsId)
            )
    );
}
 
Example 15
Source Project: configuration-as-code-plugin   Source File: CredentialsTest.java    License: MIT License 6 votes vote down vote up
@ConfiguredWithCode("GlobalCredentials.yml")
@Test
public void testGlobalScopedCredentials() {
    List<StandardUsernamePasswordCredentials> creds = CredentialsProvider.lookupCredentials(StandardUsernamePasswordCredentials.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
    assertThat(creds.size(), is(1));
    assertEquals("user1", creds.get(0).getId());
    assertEquals("Administrator", creds.get(0).getUsername());
    assertEquals("secretPassword", creds.get(0).getPassword().getPlainText());

    List<BasicSSHUserPrivateKey> creds2 = CredentialsProvider.lookupCredentials(BasicSSHUserPrivateKey.class,Jenkins.getInstanceOrNull(), null, Collections.emptyList());
    assertThat(creds2.size(), is(1));
    BasicSSHUserPrivateKey basicSSHUserPrivateKey = creds2.get(0);
    assertEquals("agentuser", basicSSHUserPrivateKey.getUsername());
    assertEquals("password", basicSSHUserPrivateKey.getPassphrase().getPlainText());
    assertEquals("ssh private key used to connect ssh slaves", basicSSHUserPrivateKey.getDescription());
    assertThat(basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().size(), is(1));
    String directKey = basicSSHUserPrivateKey.getPrivateKeySource().getPrivateKeys().get(0);
    assertThat(directKey, is("sp0ds9d+skkfjf"));

}
 
Example 16
Source Project: configuration-as-code-plugin   Source File: TopReadmeTest.java    License: MIT License 6 votes vote down vote up
@Test
@ConfiguredWithReadme("README.md#0")
public void configure_demo_first_code_block() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
    final LDAPSecurityRealm securityRealm = (LDAPSecurityRealm) jenkins.getSecurityRealm();
    assertEquals(1, securityRealm.getConfigurations().size());
    assertEquals(50000, jenkins.getSlaveAgentPort());

    assertEquals(1, jenkins.getNodes().size());
    assertEquals("static-agent", jenkins.getNode("static-agent").getNodeName());

    final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
    assertEquals(1, gitTool.getInstallations().length);

    List<BasicSSHUserPrivateKey> sshPrivateKeys = CredentialsProvider.lookupCredentials(
        BasicSSHUserPrivateKey.class, jenkins, ACL.SYSTEM, Collections.emptyList()
    );
    assertThat(sshPrivateKeys, hasSize(1));

    final BasicSSHUserPrivateKey ssh_with_passphrase = sshPrivateKeys.get(0);
    assertThat(ssh_with_passphrase.getPassphrase().getPlainText(), equalTo("ABCD"));

    final DirectEntryPrivateKeySource source = (DirectEntryPrivateKeySource) ssh_with_passphrase.getPrivateKeySource();
    assertThat(source.getPrivateKey().getPlainText(), equalTo("s3cr3t"));
}
 
Example 17
Source Project: yet-another-docker-plugin   Source File: DockerConnector.java    License: MIT License 6 votes vote down vote up
@RequirePOST
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    List<StandardCredentials> credentials =
            CredentialsProvider.lookupCredentials(StandardCredentials.class,
                    context,
                    ACL.SYSTEM,
                    Collections.emptyList());

    return new CredentialsListBoxModel()
            .includeEmptyValue()
            .withMatching(CredentialsMatchers.always(), credentials);
}
 
Example 18
Source Project: credentials-binding-plugin   Source File: BindingStepTest.java    License: 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 19
Source Project: acunetix-plugin   Source File: BuildScanner.java    License: MIT License 6 votes vote down vote up
public ListBoxModel doFillGApiKeyIDItems(
        @AncestorInPath Item item) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (item == null) {
        if (!Jenkins.getInstance().hasPermission(Jenkins.ADMINISTER)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    } else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return result.includeCurrentValue(gApiKeyID);
        }
    }
    if (gApiKeyID != null) {
        result.includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.withId(gApiKeyID)));
    }
    return result
            .includeMatchingAs(ACL.SYSTEM, Jenkins.getInstance(), StringCredentials.class,
                    Collections.<DomainRequirement> emptyList(), CredentialsMatchers.allOf(CredentialsMatchers.instanceOf(StringCredentials.class)));
}
 
Example 20
Source Project: docker-commons-plugin   Source File: DockerRegistryEndpoint.java    License: MIT License 6 votes vote down vote up
/**
 * Plugins that want to refer to a {@link IdCredentials} should do so via ID string,
 * and use this method to resolve it and convert to {@link DockerRegistryToken}.
 *
 * @param context
 *       If you are a build step trying to access DockerHub in the context of a build/job,
 *       specify that build. Otherwise null. If you are scoped to something else, you might
 *       have to interact with {@link CredentialsProvider} directly.
 */
@CheckForNull DockerRegistryToken getToken(@CheckForNull Run context) {
    if (credentialsId == null) {
        return null;
    }

    List<DomainRequirement> requirements = Collections.emptyList();
    try {
        requirements = Collections.<DomainRequirement>singletonList(new HostnameRequirement(getEffectiveUrl().getHost()));
    } catch (IOException e) {
        LOGGER.log(Level.FINE, "Unable to add domain requirement for endpoint URL", e);
    }

    return AuthenticationTokens.convert(DockerRegistryToken.class,
            CredentialsProvider.findCredentialById(credentialsId, IdCredentials.class, context, requirements));
}
 
Example 21
public static Optional<StandardCredentials> findCredentials(
    final Item item, final String credentialsId, final String uri) {
  if (isNullOrEmpty(credentialsId)) {
    return absent();
  }
  return fromNullable(
      CredentialsMatchers.firstOrNull(
          CredentialsProvider.lookupCredentials(
              StandardCredentials.class,
              item,
              item instanceof Queue.Task
                  ? Tasks.getAuthenticationOf((Queue.Task) item)
                  : ACL.SYSTEM,
              URIRequirementBuilder.fromUri(uri).build()),
          CredentialsMatchers.allOf(
              CredentialsMatchers.withId(credentialsId),
              CredentialsMatchers.anyOf(
                  CredentialsMatchers.instanceOf(StandardUsernamePasswordCredentials.class),
                  CredentialsMatchers.instanceOf(StringCredentials.class)))));
}
 
Example 22
Source Project: blueocean-plugin   Source File: BlueOceanCredentialsProvider.java    License: MIT License 6 votes vote down vote up
@Nonnull
@Override
public List<Credentials> getCredentials(@Nonnull Domain domain) {
    final List<Credentials> result = new ArrayList<>(1);
    if (domain.equals(FolderPropertyImpl.this.domain)) {
        final User proxyUser = User.get(getUser(), false, Collections.emptyMap());
        if (proxyUser != null) {
            try (ACLContext ignored = ACL.as(proxyUser.impersonate())) {
                for (CredentialsStore s : CredentialsProvider.lookupStores(proxyUser)) {
                    for (Domain d : s.getDomains()) {
                        if (d.test(PROXY_REQUIREMENT)) {
                            result.addAll(filter(s.getCredentials(d), withId(getId())));
                        }
                    }
                }
            } catch (UsernameNotFoundException ex) {
                logger.warn("BlueOceanCredentialsProvider.StoreImpl#getCredentials(): Username attached to credentials can not be found");
            }
        }
    }
    return result;
}
 
Example 23
@Test
public void basicsPipeline() throws Exception {
	// create the Credentials
	String alias = "androiddebugkey";
	String password = "android";
	StandardCertificateCredentials c = new CertificateCredentialsImpl(CredentialsScope.GLOBAL, "my-certificate", alias,
			password, new CertificateCredentialsImpl.FileOnMasterKeyStoreSource(certificate.getAbsolutePath()));
	CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c);
	// create the Pipeline job
	WorkflowJob p = r.jenkins.createProject(WorkflowJob.class, "p");
	String pipelineScript = IOUtils.toString(getTestResourceInputStream("basicsPipeline-Jenkinsfile"));
	p.setDefinition(new CpsFlowDefinition(pipelineScript, true));
	// copy resources into workspace
	FilePath workspace = r.jenkins.getWorkspaceFor(p);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.bat", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step1.sh", 0755);
	copyTestResourceIntoWorkspace(workspace, "basicsPipeline-step2.sh", 0755);
	// execute the pipeline
	WorkflowRun b = p.scheduleBuild2(0).waitForStart();
	r.waitForCompletion(b);
	r.assertBuildStatusSuccess(b);
}
 
Example 24
Source Project: credentials-binding-plugin   Source File: SSHUserPrivateKeyTest.java    License: MIT License 5 votes vote down vote up
@Test public void configRoundTrip() throws Exception {
    story.addStep(new Statement() {
        @Override public void evaluate() throws Throwable {
            SSHUserPrivateKey c = new DummyPrivateKey("creds", "bob", "secret", "the-key");
            CredentialsProvider.lookupStores(story.j.jenkins).iterator().next().addCredentials(Domain.global(), c);
            SSHUserPrivateKeyBinding binding = new SSHUserPrivateKeyBinding("keyFile", "creds");
            binding.setPassphraseVariable("passphrase");
            binding.setUsernameVariable("user");
            BindingStep s = new StepConfigTester(story.j).configRoundTrip(new BindingStep(
                    Collections.<MultiBinding>singletonList(binding)));
            story.j.assertEqualDataBoundBeans(s.getBindings(), Collections.singletonList(binding));
        }
    });
}
 
Example 25
Source Project: gitlab-branch-source-plugin   Source File: GitLabServer.java    License: MIT License 5 votes vote down vote up
/**
 * Looks up for Personal Access Token
 *
 * @return {@link PersonalAccessToken}
 */
public PersonalAccessToken getCredentials() {
    Jenkins jenkins = Jenkins.get();
    jenkins.checkPermission(CredentialsProvider.USE_OWN);
    return StringUtils.isBlank(credentialsId) ? null : CredentialsMatchers.firstOrNull(
        lookupCredentials(
            PersonalAccessToken.class,
            jenkins,
            ACL.SYSTEM,
            fromUri(defaultIfBlank(serverUrl, GITLAB_SERVER_URL)).build()
        ), withId(credentialsId));
}
 
Example 26
Source Project: gitlab-branch-source-plugin   Source File: GitLabSCMNavigator.java    License: MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath SCMSourceOwner context,
    @QueryParameter String serverName,
    @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
            && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
        context instanceof Queue.Task
            ? ((Queue.Task) context).getDefaultAuthentication()
            : ACL.SYSTEM,
        context,
        StandardUsernameCredentials.class,
        fromUri(getServerUrlFromName(serverName)).build(),
        GitClient.CREDENTIALS_MATCHER
    );
    return result;
}
 
Example 27
Source Project: gitlab-branch-source-plugin   Source File: SSHCheckoutTrait.java    License: MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public ListBoxModel doFillCredentialsIdItems(@CheckForNull @AncestorInPath Item context,
    @QueryParameter String serverUrl,
    @QueryParameter String credentialsId) {
    StandardListBoxModel result = new StandardListBoxModel();
    if (context == null) {
        if (!Jenkins.get().hasPermission(Jenkins.ADMINISTER)) {
            // must have admin if you want the list without a context
            result.includeCurrentValue(credentialsId);
            return result;
        }
    } else {
        if (!context.hasPermission(Item.EXTENDED_READ)
            && !context.hasPermission(CredentialsProvider.USE_ITEM)) {
            // must be able to read the configuration or use the item credentials if you want the list
            result.includeCurrentValue(credentialsId);
            return result;
        }
    }
    result.includeEmptyValue();
    result.includeMatchingAs(
        context instanceof Queue.Task
            ? ((Queue.Task) context).getDefaultAuthentication()
            : ACL.SYSTEM,
        context,
        StandardUsernameCredentials.class,
        URIRequirementBuilder.fromUri(serverUrl).build(),
        CredentialsMatchers.instanceOf(SSHUserPrivateKey.class)
    );
    return result;
}
 
Example 28
@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 29
public ListBoxModel doFillCredentialsItems() {
    final ListBoxModel model = new ListBoxModel();

    DomainRequirement domain = new DomainRequirement();
    for (AwsKeyCredentials credentials : CredentialsProvider.lookupCredentials(AwsKeyCredentials.class, Jenkins.getInstance(), ACL.SYSTEM, domain)) {
        model.add(credentials.getId());
    }
    return model;
}
 
Example 30
Source Project: warnings-ng-plugin   Source File: AxivionSuite.java    License: MIT License 5 votes vote down vote up
/**
 * Checks whether valid credentials are given.
 *
 * @param item
 *         jenkins configuration
 * @param credentialsId
 *         id of the stored credentials pair
 *
 * @return {@link FormValidation#ok()} if credentials exist and are valid
 */
public FormValidation doCheckCredentialsId(
        @AncestorInPath final Item item, @QueryParameter final String credentialsId) {
    if (StringUtils.isBlank(credentialsId)) {
        return FormValidation.error("You have to provide credentials.");
    }
    if (item == null) {
        if (!new JenkinsFacade().hasPermission(Jenkins.ADMINISTER)) {
            return FormValidation.ok();
        }
    }
    else {
        if (!item.hasPermission(Item.EXTENDED_READ)
                && !item.hasPermission(CredentialsProvider.USE_ITEM)) {
            return FormValidation.ok();
        }
    }

    if (CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(
                    StandardUsernamePasswordCredentials.class,
                    item,
                    ACL.SYSTEM,
                    Collections.emptyList()),
            CredentialsMatchers.withId(credentialsId))
            == null) {
        return FormValidation.error("Cannot find currently selected credentials.");
    }
    return FormValidation.ok();
}