com.cloudbees.plugins.credentials.CredentialsProvider Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsProvider. 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: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with 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 #2
Source File: GiteaServer.java    From gitea-plugin with 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 #3
Source File: GitPushStep.java    From simple-pull-request-job-plugin with Apache License 2.0 6 votes vote down vote up
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 #4
Source File: AWSEBDeploymentBuilder.java    From awseb-deployment-plugin with Apache License 2.0 6 votes vote down vote up
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 #5
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 #6
Source File: BlueOceanCredentialsProvider.java    From blueocean-plugin with 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 #7
Source File: CertificateMultiBindingTest.java    From credentials-binding-plugin with MIT License 6 votes vote down vote up
@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 #8
Source File: ZipFileBinding.java    From credentials-binding-plugin with 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 #9
Source File: ZipFileBindingTest.java    From credentials-binding-plugin with 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 #10
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 #11
Source File: VaultBuildWrapper.java    From hashicorp-vault-plugin with 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 #12
Source File: CredentialsTest.java    From configuration-as-code-plugin with 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 #13
Source File: GerritApiBuilder.java    From gerrit-code-review-plugin with Apache License 2.0 6 votes vote down vote up
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 #14
Source File: TopReadmeTest.java    From configuration-as-code-plugin with 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 #15
Source File: Connector.java    From github-branch-source-plugin with 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 #16
Source File: DockerConnector.java    From yet-another-docker-plugin with 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 #17
Source File: DockerRegistryEndpoint.java    From docker-commons-plugin with 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 #18
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 #19
Source File: BuildScanner.java    From acunetix-plugin with 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 File: CredentialsHelper.java    From violation-comments-to-github-plugin with MIT License 6 votes vote down vote up
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 #21
Source File: VaultStringCredentialIT.java    From hashicorp-vault-plugin with 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 #22
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 #23
Source File: CredentialApiTest.java    From blueocean-plugin with 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 #24
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 5 votes vote down vote up
private static @CheckForNull CredentialsStore findUserStoreFirstOrNull(User user){
    for(CredentialsStore s: CredentialsProvider.lookupStores(user)){
        if(s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)){
            return s;
        }
    }
    return null;
}
 
Example #25
Source File: SSHCheckoutTrait.java    From github-branch-source-plugin with MIT License 5 votes vote down vote up
/**
 * Validation for checkout credentials.
 *
 * @param context   the context.
 * @param serverUrl the server url.
 * @param value     the current selection.
 * @return the validation results
 */
@Restricted(NoExternalUse.class)
@SuppressWarnings("unused") // stapler form binding
public FormValidation doCheckCredentialsId(@CheckForNull @AncestorInPath Item context,
                                           @QueryParameter String serverUrl,
                                           @QueryParameter String value) {
    if (context == null
            ? !Jenkins.get().hasPermission(Jenkins.ADMINISTER)
            : !context.hasPermission(Item.EXTENDED_READ)) {
        return FormValidation.ok();
    }
    if (StringUtils.isBlank(value)) {
        // use agent key
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(
            SSHUserPrivateKey.class,
            context,
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.ok();
    }
    if (CredentialsMatchers.firstOrNull(CredentialsProvider.lookupCredentials(
            StandardUsernameCredentials.class,
            context,
            context instanceof Queue.Task ? ((Queue.Task) context).getDefaultAuthentication() : ACL.SYSTEM,
            URIRequirementBuilder.fromUri(serverUrl).build()),
            CredentialsMatchers.withId(value)) != null) {
        return FormValidation.error(Messages.SSHCheckoutTrait_incompatibleCredentials());
    }
    return FormValidation.warning(Messages.SSHCheckoutTrait_missingCredentials());
}
 
Example #26
Source File: MarathonBuilderUtils.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Get the credentials identified by the given id from the Jenkins credential store.
 *
 * @param <T>              credential type
 * @param credentialsId    The id for the credentials
 * @param credentialsClass The class of credentials to return
 * @return Jenkins credentials
 */
public static <T extends Credentials> T getJenkinsCredentials(final String credentialsId, final Class<T> credentialsClass) {
    if (StringUtils.isEmpty(credentialsId))
        return null;
    return CredentialsMatchers.firstOrNull(
            CredentialsProvider.lookupCredentials(credentialsClass,
                    Jenkins.getInstance(), ACL.SYSTEM, Collections.<DomainRequirement>emptyList()),
            CredentialsMatchers.withId(credentialsId)
    );
}
 
Example #27
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 #28
Source File: DockerCreateContainer.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public static ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    AccessControlled ac = (context instanceof AccessControlled ? (AccessControlled) context : Jenkins.getInstance());
    if (!ac.hasPermission(Jenkins.ADMINISTER)) {
        return new ListBoxModel();
    }

    return new SSHUserListBoxModel().withMatching(
            SSHAuthenticator.matcher(Connection.class),
            CredentialsProvider.lookupCredentials(
                    StandardUsernameCredentials.class,
                    context,
                    ACL.SYSTEM,
                    SSHLauncher.SSH_SCHEME)
    );
}
 
Example #29
Source File: PropertiesSecretSourceTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithCode("PropertiesSecretSourceTest.yaml")
public void test_reading_secrets_from_properties() throws Exception {
    List<UsernamePasswordCredentials> credentialList = CredentialsProvider
        .lookupCredentials(UsernamePasswordCredentials.class,
            Jenkins.getInstanceOrNull(), null, Collections.emptyList());
    assertEquals(1, credentialList.size());

    UsernamePasswordCredentials credentials = credentialList.get(0);

    // https://leahneukirchen.org/blog/archive/2019/10/ken-thompson-s-unix-password.html
    assertEquals("ken", credentials.getUsername());
    assertEquals("p/q2-q4!", credentials.getPassword().getPlainText());
}
 
Example #30
Source File: MarathonRecorderTest.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Test that a JSON credential with "jenkins_token" uses the token value as the authentication token.
 *
 * @throws Exception
 */
@Test
public void testRecorderJSONToken() throws Exception {
    final FreeStyleProject                       project         = j.createFreeStyleProject();
    final String                                 responseStr     = "{\"version\": \"one\", \"deploymentId\": \"someid-here\"}";
    final SystemCredentialsProvider.ProviderImpl system          = ExtensionList.lookup(CredentialsProvider.class).get(SystemCredentialsProvider.ProviderImpl.class);
    final CredentialsStore                       systemStore     = system.getStore(j.getInstance());
    final String                                 tokenValue      = "my secret token";
    final String                                 credentialValue = "{\"field1\":\"some value\", \"jenkins_token\":\"" + tokenValue + "\"}";
    final Secret                                 secret          = Secret.fromString(credentialValue);
    final StringCredentials                      credential      = new StringCredentialsImpl(CredentialsScope.GLOBAL, "jsontoken", "a token for JSON token test", secret);
    TestUtils.enqueueJsonResponse(httpServer, responseStr);
    systemStore.addCredentials(Domain.global(), credential);

    // add builders
    addBuilders(TestUtils.loadFixture("idonly.json"), project);

    // add post-builder
    addPostBuilders(project, "jsontoken");

    final FreeStyleBuild build = j.assertBuildStatusSuccess(project.scheduleBuild2(0).get());
    j.assertLogContains("[Marathon]", build);

    // handler assertions
    assertEquals("Only 1 request should be made", 1, httpServer.getRequestCount());
    RecordedRequest request           = httpServer.takeRequest();
    final String    authorizationText = request.getHeader("Authorization");
    assertEquals("Token does not match", "token=" + tokenValue, authorizationText);
}