Java Code Examples for com.cloudbees.plugins.credentials.CredentialsProvider#lookupCredentials()

The following examples show how to use com.cloudbees.plugins.credentials.CredentialsProvider#lookupCredentials() . 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: ConfigurationAsCodeTest.java    From gitlab-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void should_support_configuration_as_code() {
    List<GitLabServer> servers = GitLabServers.get().getServers();
    assertThat(servers.size(), is(1));
    GitLabServer server = servers.get(0);
    assertThat(server.getServerUrl(), is("https://gitlab.com"));
    assertThat(server.getName(), matchesPattern("gitlab-[0-9]{4}"));
    assertThat(server.isManageWebHooks(), is(true));
    assertThat(server.isManageSystemHooks(), is(true));
    assertThat(server.getHooksRootUrl(), is("https://jenkins.intranet/"));

    List<PersonalAccessTokenImpl> credentials = CredentialsProvider.lookupCredentials(
        PersonalAccessTokenImpl.class, j.jenkins, ACL.SYSTEM,
        Collections.emptyList()
    );
    assertThat(credentials, hasSize(1));
    final PersonalAccessTokenImpl credential = credentials.get(0);
    assertThat(credential.getToken().getPlainText(), is("XfsqZvVtAx5YCph5bq3r"));
    assertThat(credential.getToken().getEncryptedValue(), is(not("XfsqZvVtAx5YCph5bq3r")));
}
 
Example 2
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 3
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 4
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 5
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 6
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 7
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 8
Source File: AxivionSuite.java    From warnings-ng-plugin with MIT License 6 votes vote down vote up
private UsernamePasswordCredentials withValidCredentials() {
    final List<StandardUsernamePasswordCredentials> all =
            CredentialsProvider.lookupCredentials(
                    StandardUsernamePasswordCredentials.class,
                    (Item) null,
                    ACL.SYSTEM,
                    Collections.emptyList());

    StandardUsernamePasswordCredentials jenkinsCredentials =
            CredentialsMatchers.firstOrNull(all,
                    CredentialsMatchers.withId(credentialsId));

    if (jenkinsCredentials == null) {
        throw new ParsingException("Could not find the credentials for " + credentialsId);
    }

    return new UsernamePasswordCredentials(
            jenkinsCredentials.getUsername(),
            Secret.toString(jenkinsCredentials.getPassword()));
}
 
Example 9
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 10
Source File: CredentialsTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@ConfiguredWithCode("CredentialsWithDomain.yml")
@Test
public void testDomainScopedCredentials() {
    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("secret", creds.get(0).getPassword().getPlainText());
}
 
Example 11
Source File: SignArtifactPlugin.java    From jenkins-android-signing with Apache License 2.0 5 votes vote down vote up
private KeystoreCredentials getKeystore(String keyStoreName) {
    List<KeystoreCredentials> creds = CredentialsProvider.lookupCredentials(KeystoreCredentials.class, Jenkins.getInstance(), ACL.SYSTEM);
    for(KeystoreCredentials cred : creds) {
        if(cred.getId().equals(keyStoreName)){
            return cred;
        }
    }
    return null;
}
 
Example 12
Source File: SignArtifactPlugin.java    From jenkins-android-signing with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillKeystoreItems() {
    ListBoxModel items = new ListBoxModel();
    for (KeystoreCredentials gpgKey : CredentialsProvider.lookupCredentials(KeystoreCredentials.class, Jenkins.getInstance(), ACL.SYSTEM)) {
        items.add(gpgKey.getDescription(), gpgKey.getId());
    }
    return items;
}
 
Example 13
Source File: GlobalKafkaConfiguration.java    From remoting-kafka-plugin with MIT License 5 votes vote down vote up
@CheckForNull
private StandardUsernamePasswordCredentials getCredential(@Nonnull String id) {
    StandardUsernamePasswordCredentials credential = null;
    List<StandardUsernamePasswordCredentials> credentials = CredentialsProvider.lookupCredentials(
            StandardUsernamePasswordCredentials.class, Jenkins.get(), ACL.SYSTEM, Collections.emptyList());
    IdMatcher matcher = new IdMatcher(id);
    for (StandardUsernamePasswordCredentials c : credentials) {
        if (matcher.matches(c)) {
            credential = c;
        }
    }
    return credential;
}
 
Example 14
Source File: Environment.java    From jenkins-deployment-dashboard-plugin with MIT License 5 votes vote down vote up
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 15
Source File: EnvironmentTagBuilder.java    From jenkins-deployment-dashboard-plugin with MIT License 5 votes vote down vote up
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 16
Source File: GitHubStatusNotificationStep.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath Item project) {
    AbstractIdCredentialsListBoxModel result = new StandardListBoxModel();
    if (!project.hasPermission(Item.CONFIGURE)) {
        return result;
    }
    List<UsernamePasswordCredentials> credentialsList = CredentialsProvider.lookupCredentials(UsernamePasswordCredentials.class, project, ACL.SYSTEM);
    for (UsernamePasswordCredentials credential : credentialsList) {
        result = result.with((IdCredentials) credential);
    }
    return result;
}
 
Example 17
Source File: SecretRetriever.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
public Optional<String> getSecretFor(final String credentialsId) {

        final List<StringCredentials> credentials =
                CredentialsProvider.lookupCredentials(
                        StringCredentials.class,
                        Jenkins.get(),
                        ACL.SYSTEM,
                        Collections.emptyList());
        final CredentialsMatcher matcher = CredentialsMatchers.withId(credentialsId);

        return Optional.ofNullable(CredentialsMatchers.firstOrNull(credentials, matcher))
                .flatMap(creds -> Optional.ofNullable(creds.getSecret()))
                .flatMap(secret -> Optional.ofNullable(secret.getPlainText()));
    }
 
Example 18
Source File: ConduitCredentialsDescriptor.java    From phabricator-jenkins-plugin with MIT License 5 votes vote down vote up
private static List<ConduitCredentials> availableCredentials(Job owner) {
    return CredentialsProvider.lookupCredentials(
            ConduitCredentials.class,
            owner,
            null,
            new ArrayList<DomainRequirement>()
    );
}
 
Example 19
Source File: DockerRegistryCredential.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems(@AncestorInPath ItemGroup context) {
    List<DockerRegistryAuthCredentials> credentials =
            CredentialsProvider.lookupCredentials(DockerRegistryAuthCredentials.class, context, ACL.SYSTEM,
                    Collections.emptyList());

    return new CredentialsListBoxModel()
            .includeEmptyValue()
            .withMatching(CredentialsMatchers.always(), credentials);
}
 
Example 20
Source File: SystemCredentialsTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
    @ConfiguredWithCode("SystemCredentialsTest.yml")
    public void configure_system_credentials() throws Exception {
        Jenkins jenkins = Jenkins.get();

        List<UsernamePasswordCredentials> ups = CredentialsProvider.lookupCredentials(
                UsernamePasswordCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList()
        );
        assertThat(ups, hasSize(1));
        final UsernamePasswordCredentials up = ups.get(0);
        assertThat(up.getPassword().getPlainText(), equalTo("1234"));

        ConfiguratorRegistry registry = ConfiguratorRegistry.get();
        final ConfigurationContext context = new ConfigurationContext(registry);
        final CNode node = context.lookup(up.getClass()).describe(up, context);
        assertThat(node.asMapping().getScalarValue("password"), not(equals("1234")));


        List<CertificateCredentials> certs = CredentialsProvider.lookupCredentials(
                CertificateCredentials.class, jenkins, ACL.SYSTEM, Collections.emptyList()
        );
        assertThat(certs, hasSize(0));
//       TODO: add test for uploaded certificate
//        assertThat(certs.get(0).getPassword().getPlainText(), equalTo("ABCD"));

        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"));


        // credentials should not appear in plain text in log
        for (LogRecord logRecord : log.getRecords()) {
            assertThat(logRecord.getMessage(), not(containsString("1234")));
            assertThat(logRecord.getMessage(), not(containsString("ABCD")));
        }


    }