com.cloudbees.plugins.credentials.Credentials Java Examples

The following examples show how to use com.cloudbees.plugins.credentials.Credentials. 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: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 6 votes vote down vote up
@Test
public void buildWithWrongCredentialsMustFail() throws Exception {

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
    "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
    "credentialsId: 'dummy', description: 'All tests are OK', " +
    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.CREDENTIALS_LOGIN_INVALID, b1);
}
 
Example #2
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 #3
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void createCredentialsInUserStore(@Nonnull Credentials credential, @Nonnull User user,
                                                @Nonnull String domainName, @Nonnull List<DomainSpecification> domainSpecifications)
        throws IOException {
    CredentialsStore store= findUserStoreFirstOrNull(user);

    if(store == null){
        throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store", user.getId()));
    }

    Domain domain = findOrCreateDomain(store, domainName, domainSpecifications);

    if(!store.addCredentials(domain, credential)){
        throw new ServiceException.UnexpectedErrorException("Failed to add credential to domain");
    }

}
 
Example #4
Source File: CredentialsUtils.java    From blueocean-plugin with MIT License 6 votes vote down vote up
public static void updateCredentialsInUserStore(@Nonnull Credentials current, @Nonnull Credentials replacement,
                                                @Nonnull User user,
                                                @Nonnull String domainName, @Nonnull List<DomainSpecification> domainSpecifications)
        throws IOException {
    CredentialsStore store= findUserStoreFirstOrNull(user);

    if(store == null){
        throw new ServiceException.ForbiddenException(String.format("Logged in user: %s doesn't have writable credentials store",
                user.getId()));
    }

    Domain domain = findOrCreateDomain(store, domainName, domainSpecifications);

    if(!store.updateCredentials(domain, current, replacement)){
        throw new ServiceException.UnexpectedErrorException("Failed to update credential to domain");
    }
}
 
Example #5
Source File: MarathonBuilderImpl.java    From marathon-plugin with Apache License 2.0 6 votes vote down vote up
/**
 * Construct a Marathon client based on the provided credentialsId and execute an update for the configuration's
 * Marathon application.
 *
 * @param credentialsId A string ID for a credential within Jenkin's Credential store
 * @throws MarathonException thrown if the Marathon service has an error
 */
private void doUpdate(final String credentialsId) throws MarathonException {
    final Credentials credentials = MarathonBuilderUtils.getJenkinsCredentials(credentialsId, Credentials.class);

    Marathon client;

    if (credentials instanceof UsernamePasswordCredentials) {
        client = getMarathonClient((UsernamePasswordCredentials) credentials);
    } else if (credentials instanceof StringCredentials) {
        client = getMarathonClient((StringCredentials) credentials);
    } else {
        client = getMarathonClient();
    }

    if (client != null) {
        client.updateApp(getApp().getId(), getApp(), config.getForceUpdate());
    }
}
 
Example #6
Source File: WithMavenStepExecution2.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Override
public String apply(@javax.annotation.Nullable Credentials credentials) {
    if (credentials == null)
        return "null";

    String result = ClassUtils.getShortName(credentials.getClass()) + "[";
    if (credentials instanceof IdCredentials) {
        IdCredentials idCredentials = (IdCredentials) credentials;
        result += "id: " + idCredentials.getId() + ",";
    }

    if (credentials instanceof UsernameCredentials) {
        UsernameCredentials usernameCredentials = (UsernameCredentials) credentials;
        result += "username: " + usernameCredentials.getUsername() + "";
    }
    result += "]";
    return result;
}
 
Example #7
Source File: MaskPasswordsConsoleLogFilter.java    From pipeline-maven-plugin with MIT License 6 votes vote down vote up
@Nonnull
protected static Collection<String> toString(@Nonnull Iterable<Credentials> credentials) {
    List<String> result = new ArrayList<>();
    for (Credentials creds : credentials) {
        if (creds instanceof PasswordCredentials) {
            PasswordCredentials passwordCredentials = (PasswordCredentials) creds;
            result.add(passwordCredentials.getPassword().getPlainText());
        } else if (creds instanceof SSHUserPrivateKey) {
            SSHUserPrivateKey sshUserPrivateKey = (SSHUserPrivateKey) creds;
            Secret passphrase = sshUserPrivateKey.getPassphrase();
            if (passphrase != null) {
                result.add(passphrase.getPlainText());
            }
            // omit the private key, there
        } else {
            LOGGER.log(Level.FINE, "Skip masking of unsupported credentials type {0}: {1}", new Object[]{creds.getClass(), creds.getDescriptor().getDisplayName()});
        }
    }
    return result;
}
 
Example #8
Source File: GitHubAppCredentialsJCasCCompatibilityTest.java    From github-branch-source-plugin with MIT License 6 votes vote down vote up
@Test
public void should_support_configuration_as_code() {
    List<DomainCredentials> domainCredentials = SystemCredentialsProvider.getInstance()
            .getDomainCredentials();

    assertThat(domainCredentials.size(), is(1));
    List<Credentials> credentials = domainCredentials.get(0).getCredentials();
    assertThat(credentials.size(), is(1));

    Credentials credential = credentials.get(0);
    assertThat(credential, instanceOf(GitHubAppCredentials.class));
    GitHubAppCredentials gitHubAppCredentials = (GitHubAppCredentials) credential;

    assertThat(gitHubAppCredentials.getAppID(), is("1111"));
    assertThat(gitHubAppCredentials.getDescription(), is("GitHub app 1111"));
    assertThat(gitHubAppCredentials.getId(), is("github-app"));
    assertThat(gitHubAppCredentials.getPrivateKey(), hasPlainText(GITHUB_APP_KEY));
}
 
Example #9
Source File: DockerAuthConfig.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
@CheckForNull
public AuthConfig getAuthConfig() {
    if (StringUtils.isEmpty(credentialsId)) {
        return null;
    }

    if (StringUtils.isNotBlank(credentialsId)) {
        // hostname requirements?
        Credentials credentials = lookupSystemCredentials(credentialsId);
        if (credentials instanceof DockerRegistryAuthCredentials) {
            final DockerRegistryAuthCredentials authCredentials = (DockerRegistryAuthCredentials) credentials;
            return authCredentials.getAuthConfig();
        }
    }
    return null;
}
 
Example #10
Source File: DockerBuildImage.java    From yet-another-docker-plugin with MIT License 6 votes vote down vote up
/**
 * Fill additional object with resolved creds.
 * For example before transfering object to remote.
 */
public void resolveCreds() {
    final AuthConfigurations authConfigs = new AuthConfigurations();

    for (Map.Entry<String, String> entry : creds.entrySet()) {
        final String registry = entry.getKey();
        final String credId = entry.getValue();
        final Credentials credentials = ClientBuilderForConnector.lookupSystemCredentials(credId);
        if (credentials instanceof UsernamePasswordCredentials) {
            final UsernamePasswordCredentials upCreds = (UsernamePasswordCredentials) credentials;
            final AuthConfig authConfig = new AuthConfig()
                    .withRegistryAddress(registry)
                    .withPassword(upCreds.getPassword())
                    .withUsername(upCreds.getUserName());
            authConfigs.addConfig(authConfig);
        } else if (credentials instanceof DockerRegistryAuthCredentials) {
            final DockerRegistryAuthCredentials authCredentials = (DockerRegistryAuthCredentials) credentials;
            authConfigs.addConfig(
                    authCredentials.getAuthConfig().withRegistryAddress(registry)
            );
        }
    }
    this.authConfigurations = authConfigs;
}
 
Example #11
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 6 votes vote down vote up
@Test
public void buildWithWrongCredentialsMustFailEnterprise() throws Exception {

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.CREDENTIALS_LOGIN_INVALID, b1);
}
 
Example #12
Source File: CredentialsHelper.java    From git-changelog-plugin with MIT License 5 votes vote down vote up
private static <C extends Credentials> List<C> getAllCredentials(Class<C> type) {
  ItemGroup<?> itemGroup = null;
  Authentication authentication = SYSTEM;
  DomainRequirement domainRequirement = null;

  return lookupCredentials(type, itemGroup, authentication, domainRequirement);
}
 
Example #13
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 #14
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildEnterprise() throws Exception {

    GitHubBuilder ghb = PowerMockito.mock(GitHubBuilder.class);
    PowerMockito.when(ghb.withProxy(Matchers.<Proxy>anyObject())).thenReturn(ghb);
    PowerMockito.when(ghb.withOAuthToken(anyString(), anyString())).thenReturn(ghb);
    PowerMockito.when(ghb.withEndpoint("https://api.example.com")).thenReturn(ghb);
    PowerMockito.whenNew(GitHubBuilder.class).withNoArguments().thenReturn(ghb);
    GitHub gh = PowerMockito.mock(GitHub.class);
    PowerMockito.when(ghb.build()).thenReturn(gh);
    PowerMockito.when(gh.isCredentialValid()).thenReturn(true);
    GHRepository repo = PowerMockito.mock(GHRepository.class);
    GHUser user = PowerMockito.mock(GHUser.class);
    GHCommit commit = PowerMockito.mock(GHCommit.class);
    PowerMockito.when(user.getRepository(anyString())).thenReturn(repo);
    PowerMockito.when(gh.getUser(anyString())).thenReturn(user);
    PowerMockito.when((repo.getCommit(anyString()))).thenReturn(commit);

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', gitApiUrl:'https://api.example.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #15
Source File: SecretRetrieverTest.java    From atlassian-jira-software-cloud-plugin with Apache License 2.0 5 votes vote down vote up
private void setupCredentials(String credentialId, String secret) throws Exception {
    final CredentialsStore credentialsStore =
            CredentialsProvider.lookupStores(jRule.jenkins).iterator().next();
    final Domain domain = Domain.global();
    final Credentials credentials =
            new StringCredentialsImpl(
                    CredentialsScope.GLOBAL, credentialId, "", Secret.fromString(secret));
    credentialsStore.addCredentials(domain, credentials);
}
 
Example #16
Source File: DcosAuthImpl.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
@Override
public boolean updateTokenCredentials(final Credentials tokenCredentials) throws AuthenticationException {
    if (tokenCredentials instanceof StringCredentials) {
        final StringCredentials oldCredentials = (StringCredentials) tokenCredentials;

        if (credentials != null) {
            try {
                final String token = getToken();
                if (token == null) {
                    // TODO: better message somewhere in getToken flow of what happened?
                    final String errorMessage = "Failed to retrieve authentication token from DC/OS.";
                    LOGGER.warning(errorMessage);
                    throw new AuthenticationException(errorMessage);
                }
                final StringCredentials updatedCredentials = newTokenCredentials(oldCredentials, token);
                return doTokenUpdate(oldCredentials.getId(), updatedCredentials);
            } catch (IOException e) {
                LOGGER.warning(e.getMessage());
                throw new AuthenticationException(e.getMessage());
            }
        }
    } else {
        LOGGER.warning("Invalid credential type, expected String Credentials, received: " + tokenCredentials.getClass().getName());
    }

    return false;
}
 
Example #17
Source File: TokenAuthProvider.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
/**
 * Helper method to update tokenCredentials with contents of creds.
 * <p>
 * This searches all domains for the id associated with tokenCredentials and updates the first credential it finds.
 *
 * @param tokenId Existing credentials that should be updated.
 * @param creds   New credentials
 * @throws IOException If problems reading or writing to Jenkins Credential Store
 */
boolean doTokenUpdate(final String tokenId, final Credentials creds) throws IOException {
    final SystemCredentialsProvider.ProviderImpl systemProvider = ExtensionList.lookup(CredentialsProvider.class)
            .get(SystemCredentialsProvider.ProviderImpl.class);
    if (systemProvider == null) return false;

    final CredentialsStore credentialsStore = systemProvider.getStore(Jenkins.getInstance());
    if (credentialsStore == null) return false;

    /*
        Walk through all domains and credentials for each domain to find a credential with the matching id.
     */
    for (final Domain d : credentialsStore.getDomains()) {
        for (Credentials c : credentialsStore.getCredentials(d)) {
            if (!(c instanceof StringCredentials)) continue;

            final StringCredentials stringCredentials = (StringCredentials) c;
            if (stringCredentials.getId().equals(tokenId)) {
                final boolean wasUpdated = credentialsStore.updateCredentials(d, c, creds);
                if (!wasUpdated) {
                    LOGGER.warning("Updating Token credential failed during update call.");
                }
                return wasUpdated;
            }
        }
    }

    // if the credential was not found, then put a warning in the console log.
    LOGGER.warning("Token credential was not found in the Credentials Store.");
    return false;
}
 
Example #18
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 #19
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 #20
Source File: ClientBuilderForConnector.java    From yet-another-docker-plugin with MIT License 5 votes vote down vote up
/**
 * Util method to find credential by id in jenkins
 *
 * @param credentialsId credentials to find in jenkins
 * @return {@link CertificateCredentials} or {@link StandardUsernamePasswordCredentials} expected
 */
public static Credentials lookupSystemCredentials(String credentialsId) {
    return firstOrNull(
            lookupCredentials(
                    Credentials.class,
                    Jenkins.getInstance(),
                    ACL.SYSTEM,
                    emptyList()
            ),
            withId(credentialsId)
    );
}
 
Example #21
Source File: GitLabCredentialMatcher.java    From gitlab-plugin with GNU General Public License v2.0 5 votes vote down vote up
@Override
public boolean matches(@NonNull Credentials credentials) {
    try {
        return credentials instanceof GitLabApiToken || credentials instanceof StringCredentials;
    } catch (Throwable e) {
        return false;
    }
}
 
Example #22
Source File: DockerCloud.java    From docker-plugin with MIT License 5 votes vote down vote up
@Restricted(NoExternalUse.class)
public static AuthConfig getAuthConfig(DockerRegistryEndpoint registry, ItemGroup context) {
    AuthConfig auth = new AuthConfig();

    // we can't use DockerRegistryEndpoint#getToken as this one do check domainRequirement based on registry URL
    // but in some context (typically, passing registry auth for `docker build`) we just can't guess this one.

    final Credentials c = firstOrNull(CredentialsProvider.lookupCredentials(
            IdCredentials.class, context, ACL.SYSTEM, Collections.EMPTY_LIST),
            withId(registry.getCredentialsId()));
    final DockerRegistryToken t = c == null ? null : AuthenticationTokens.convert(DockerRegistryToken.class, c);
    if (t == null) {
        throw new IllegalArgumentException("Invalid Credential ID " + registry.getCredentialsId());
    }
    final String token = t.getToken();
    // What docker-commons claim to be a "token" is actually configuration storage
    // see https://github.com/docker/docker-ce/blob/v17.09.0-ce/components/cli/cli/config/configfile/file.go#L214
    // i.e base64 encoded username : password
    final String decode = new String(Base64.decodeBase64(token), StandardCharsets.UTF_8);
    int i = decode.indexOf(':');
    if (i > 0) {
        String username = decode.substring(0, i);
        auth.withUsername(username);
    }
    auth.withPassword(decode.substring(i+1));
    if (registry.getUrl() != null) {
        auth.withRegistryAddress(registry.getUrl());
    }
    return auth;
}
 
Example #23
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCommitMustFail() throws Exception {

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

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_COMMIT, b1);
}
 
Example #24
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void build() throws Exception {

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

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #25
Source File: TokenAuthProvider.java    From marathon-plugin with Apache License 2.0 5 votes vote down vote up
public static TokenAuthProvider getTokenAuthProvider(final Providers provider, final Credentials credentials) {
    switch (provider) {
        case DCOS:
            return new DcosAuthImpl((StringCredentials) credentials);
        default:
            return null;
    }
}
 
Example #26
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutCredentialsMustFail() throws Exception {

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

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com', repo: 'acceptance-test-harness'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example #27
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithWrongRepoMustFail() throws Exception {

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


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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.INVALID_REPO, b1);
}
 
Example #28
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutRepoMustFail() throws Exception {

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

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}
 
Example #29
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithWrongCommitMustFail() throws Exception {

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

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.INVALID_COMMIT, b1);
}
 
Example #30
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithInferWithoutAccountMustFail() throws Exception {

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

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

    WorkflowJob p = jenkins.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify  context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487'," +
                    "repo: 'acceptance-test-harness',  " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.FAILURE, jenkins.waitForCompletion(b1));
    jenkins.assertLogContains(GitHubStatusNotificationStep.Execution.UNABLE_TO_INFER_DATA, b1);
}