Search in sources :

Example 1 with BlueOceanDomainSpecification

use of io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification in project blueocean-plugin by jenkinsci.

the class AbstractBitbucketScm method validateAndCreate.

/**
 * Request payload:
 * {
 *     "userName": "joe",
 *     "password":"****",
 *     "apiUrl":"mybitbucketserver.com"
 * }
 * @param request userName and password of bitbucket server
 *
 * @return credential id
 */
@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    User authenticatedUser = User.current();
    if (authenticatedUser == null) {
        throw new ServiceException.UnauthorizedException("No logged in user found");
    }
    String userName = (String) request.get("userName");
    String password = (String) request.get("password");
    String apiUrl = (String) request.get("apiUrl");
    validate(userName, password, apiUrl);
    final StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, createCredentialId(apiUrl), "Bitbucket server credentials", userName, password);
    // if credentials are wrong, this call will fail with 401 error
    validateCredential(apiUrl, credential);
    StandardUsernamePasswordCredentials bbCredentials = CredentialsUtils.findCredential(createCredentialId(apiUrl), StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
    try {
        if (bbCredentials == null) {
            CredentialsUtils.createCredentialsInUserStore(credential, authenticatedUser, getDomainId(), Collections.singletonList(new BlueOceanDomainSpecification()));
        } else {
            CredentialsUtils.updateCredentialsInUserStore(bbCredentials, credential, authenticatedUser, getDomainId(), Collections.singletonList(new BlueOceanDomainSpecification()));
        }
        return createResponse(credential.getId());
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
}
Also used : StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) User(hudson.model.User) ServiceException(io.jenkins.blueocean.commons.ServiceException) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) IOException(java.io.IOException) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl)

Example 2 with BlueOceanDomainSpecification

use of io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification in project blueocean-plugin by jenkinsci.

the class GithubScm method validateAndCreate.

@Override
public HttpResponse validateAndCreate(@JsonBody JSONObject request) {
    String accessToken = (String) request.get("accessToken");
    if (accessToken == null) {
        throw new ServiceException.BadRequestException("accessToken is required");
    }
    accessToken = accessToken.trim();
    try {
        User authenticatedUser = getAuthenticatedUser();
        HttpURLConnection connection = connect(String.format("%s/%s", getUri(), "user"), accessToken);
        validateAccessTokenScopes(connection);
        String data = IOUtils.toString(HttpRequest.getInputStream(connection), Charset.defaultCharset());
        GHUser user = GithubScm.getMappingObjectReader().forType(GHUser.class).readValue(data);
        if (user.getEmail() != null) {
            Mailer.UserProperty p = authenticatedUser.getProperty(Mailer.UserProperty.class);
            // the one from Github?
            if (p == null) {
                authenticatedUser.addProperty(new Mailer.UserProperty(user.getEmail()));
            }
        }
        // Now we know the token is valid. Lets find credential
        String credentialId = createCredentialId(getUri());
        StandardUsernamePasswordCredentials githubCredential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
        final StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, credentialId, getCredentialDescription(), authenticatedUser.getId(), accessToken);
        if (githubCredential == null) {
            CredentialsUtils.createCredentialsInUserStore(credential, authenticatedUser, getCredentialDomainName(), Collections.singletonList(new BlueOceanDomainSpecification()));
        } else {
            CredentialsUtils.updateCredentialsInUserStore(githubCredential, credential, authenticatedUser, getCredentialDomainName(), Collections.singletonList(new BlueOceanDomainSpecification()));
        }
        return createResponse(credential.getId());
    } catch (IOException e) {
        if (e instanceof MalformedURLException || e instanceof UnknownHostException) {
            throw new ServiceException.BadRequestException(new ErrorMessage(400, "Invalid apiUrl").add(new ErrorMessage.Error("apiUrl", ErrorMessage.Error.ErrorCodes.INVALID.toString(), e.getMessage())));
        }
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
}
Also used : MalformedURLException(java.net.MalformedURLException) GHUser(org.kohsuke.github.GHUser) User(hudson.model.User) UnknownHostException(java.net.UnknownHostException) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) Mailer(hudson.tasks.Mailer) GHUser(org.kohsuke.github.GHUser) IOException(java.io.IOException) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) HttpURLConnection(java.net.HttpURLConnection) ServiceException(io.jenkins.blueocean.commons.ServiceException) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) ErrorMessage(io.jenkins.blueocean.commons.ErrorMessage)

Example 3 with BlueOceanDomainSpecification

use of io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification in project blueocean-plugin by jenkinsci.

the class GithubOrgFolderTest method shouldFindUserStoreCredential.

@Test
public void shouldFindUserStoreCredential() throws IOException {
    //add username password credential to user's credential store in user domain and in USER scope
    User user = login();
    CredentialsStore store = null;
    for (CredentialsStore s : CredentialsProvider.lookupStores(user)) {
        if (s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)) {
            store = s;
            break;
        }
    }
    assertNotNull(store);
    store.addDomain(new Domain("github-domain", "Github Domain to store personal access token", Collections.<DomainSpecification>singletonList(new BlueOceanDomainSpecification())));
    Domain domain = store.getDomainByName("github-domain");
    StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, "github", "Github Access Token", user.getId(), "12345");
    store.addCredentials(domain, credential);
    //create another credentials with same id in system store with different description
    for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.getInstance())) {
        s.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.USER, "github", "System Github Access Token", user.getId(), "12345"));
    }
    //create org folder and attach user and credential id to it
    OrganizationFolder organizationFolder = j.createProject(OrganizationFolder.class, "demo");
    AbstractFolderProperty prop = new BlueOceanCredentialsProvider.FolderPropertyImpl(user.getId(), credential.getId(), BlueOceanCredentialsProvider.createDomain("https://api.github.com"));
    organizationFolder.addProperty(prop);
    // lookup for created credential id in system store, it should resolve to previously created user store credential
    StandardCredentials c = Connector.lookupScanCredentials(organizationFolder, "https://api.github.com", credential.getId());
    assertEquals("Github Access Token", c.getDescription());
    assertNotNull(c);
    assertTrue(c instanceof StandardUsernamePasswordCredentials);
    StandardUsernamePasswordCredentials usernamePasswordCredentials = (StandardUsernamePasswordCredentials) c;
    assertEquals(credential.getId(), usernamePasswordCredentials.getId());
    assertEquals(credential.getPassword().getPlainText(), usernamePasswordCredentials.getPassword().getPlainText());
    assertEquals(credential.getUsername(), usernamePasswordCredentials.getUsername());
    //check the domain
    Domain d = CredentialsUtils.findDomain(credential.getId(), user);
    assertNotNull(d);
    assertTrue(d.test(new BlueOceanDomainRequirement()));
    //now remove this property
    organizationFolder.getProperties().remove(prop);
    //it must resolve to system credential
    c = Connector.lookupScanCredentials(organizationFolder, null, credential.getId());
    assertEquals("System Github Access Token", c.getDescription());
}
Also used : StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) User(hudson.model.User) OrganizationFolder(jenkins.branch.OrganizationFolder) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) Domain(com.cloudbees.plugins.credentials.domains.Domain) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) DomainSpecification(com.cloudbees.plugins.credentials.domains.DomainSpecification) AbstractFolderProperty(com.cloudbees.hudson.plugins.folder.AbstractFolderProperty) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Example 4 with BlueOceanDomainSpecification

use of io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification in project blueocean-plugin by jenkinsci.

the class GitScm method createPWCredentials.

private void createPWCredentials(String credentialId, User user, @JsonBody JSONObject request, String repositoryUrl) {
    StandardUsernamePasswordCredentials existingCredential = CredentialsUtils.findCredential(credentialId, StandardUsernamePasswordCredentials.class, new BlueOceanDomainRequirement());
    String requestUsername = request.getString("userName");
    String requestPassword = request.getString("password");
    // Un-normalized repositoryUrl so the description matches user input.
    String description = String.format("%s for %s", CREDENTIAL_DESCRIPTION_PW, repositoryUrl);
    final StandardUsernamePasswordCredentials newCredential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, credentialId, description, requestUsername, requestPassword);
    try {
        if (existingCredential == null) {
            CredentialsUtils.createCredentialsInUserStore(newCredential, user, CREDENTIAL_DOMAIN_NAME, Collections.singletonList(new BlueOceanDomainSpecification()));
        } else {
            CredentialsUtils.updateCredentialsInUserStore(existingCredential, newCredential, user, CREDENTIAL_DOMAIN_NAME, Collections.singletonList(new BlueOceanDomainSpecification()));
        }
    } catch (IOException e) {
        throw new ServiceException.UnexpectedErrorException("Could not persist credential", e);
    }
}
Also used : StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) ServiceException(io.jenkins.blueocean.commons.ServiceException) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) IOException(java.io.IOException) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl)

Example 5 with BlueOceanDomainSpecification

use of io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification in project blueocean-plugin by jenkinsci.

the class GithubPipelineCreateRequestTest method shouldFindUserStoreCredential.

@Test
public void shouldFindUserStoreCredential() throws IOException {
    // add username password credential to user's credential store in user domain and in USER scope
    User user = login();
    CredentialsStore store = null;
    for (CredentialsStore s : CredentialsProvider.lookupStores(user)) {
        if (s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)) {
            store = s;
            break;
        }
    }
    assertNotNull(store);
    store.addDomain(new Domain("github-domain", "GitHub Domain to store personal access token", Collections.<DomainSpecification>singletonList(new BlueOceanDomainSpecification())));
    Domain domain = store.getDomainByName("github-domain");
    StandardUsernamePasswordCredentials credential = new UsernamePasswordCredentialsImpl(CredentialsScope.USER, "github", "GitHub Access Token", user.getId(), "12345");
    store.addCredentials(domain, credential);
    // create another credentials with same id in system store with different description
    for (CredentialsStore s : CredentialsProvider.lookupStores(Jenkins.get())) {
        s.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.USER, "github", "System GitHub Access Token", user.getId(), "12345"));
    }
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "demo");
    AbstractFolderProperty prop = new BlueOceanCredentialsProvider.FolderPropertyImpl(user.getId(), credential.getId(), BlueOceanCredentialsProvider.createDomain("https://api.github.com"));
    mp.addProperty(prop);
    // lookup for created credential id in system store, it should resolve to previously created user store credential
    StandardCredentials c = Connector.lookupScanCredentials((Item) mp, "https://api.github.com", credential.getId());
    assertEquals("GitHub Access Token", c.getDescription());
    assertNotNull(c);
    assertTrue(c instanceof StandardUsernamePasswordCredentials);
    StandardUsernamePasswordCredentials usernamePasswordCredentials = (StandardUsernamePasswordCredentials) c;
    assertEquals(credential.getId(), usernamePasswordCredentials.getId());
    assertEquals(credential.getPassword().getPlainText(), usernamePasswordCredentials.getPassword().getPlainText());
    assertEquals(credential.getUsername(), usernamePasswordCredentials.getUsername());
    // check the domain
    Domain d = CredentialsUtils.findDomain(credential.getId(), user);
    assertNotNull(d);
    assertTrue(d.test(new BlueOceanDomainRequirement()));
    // now remove this property
    mp.getProperties().remove(prop);
    // it must resolve to system credential
    c = Connector.lookupScanCredentials((Item) mp, null, credential.getId());
    assertEquals("System GitHub Access Token", c.getDescription());
}
Also used : User(hudson.model.User) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) UsernamePasswordCredentialsImpl(com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl) DomainSpecification(com.cloudbees.plugins.credentials.domains.DomainSpecification) BlueOceanDomainSpecification(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification) AbstractFolderProperty(com.cloudbees.hudson.plugins.folder.AbstractFolderProperty) StandardUsernamePasswordCredentials(com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials) WorkflowMultiBranchProject(org.jenkinsci.plugins.workflow.multibranch.WorkflowMultiBranchProject) Item(hudson.model.Item) BlueOceanDomainRequirement(io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement) CredentialsStore(com.cloudbees.plugins.credentials.CredentialsStore) Domain(com.cloudbees.plugins.credentials.domains.Domain) StandardCredentials(com.cloudbees.plugins.credentials.common.StandardCredentials) PrepareForTest(org.powermock.core.classloader.annotations.PrepareForTest) PipelineBaseTest(io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest) Test(org.junit.Test)

Aggregations

StandardUsernamePasswordCredentials (com.cloudbees.plugins.credentials.common.StandardUsernamePasswordCredentials)5 UsernamePasswordCredentialsImpl (com.cloudbees.plugins.credentials.impl.UsernamePasswordCredentialsImpl)5 BlueOceanDomainRequirement (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainRequirement)5 BlueOceanDomainSpecification (io.jenkins.blueocean.rest.impl.pipeline.credential.BlueOceanDomainSpecification)5 User (hudson.model.User)4 ServiceException (io.jenkins.blueocean.commons.ServiceException)3 IOException (java.io.IOException)3 AbstractFolderProperty (com.cloudbees.hudson.plugins.folder.AbstractFolderProperty)2 CredentialsStore (com.cloudbees.plugins.credentials.CredentialsStore)2 StandardCredentials (com.cloudbees.plugins.credentials.common.StandardCredentials)2 Domain (com.cloudbees.plugins.credentials.domains.Domain)2 DomainSpecification (com.cloudbees.plugins.credentials.domains.DomainSpecification)2 PipelineBaseTest (io.jenkins.blueocean.rest.impl.pipeline.PipelineBaseTest)2 Test (org.junit.Test)2 Item (hudson.model.Item)1 Mailer (hudson.tasks.Mailer)1 ErrorMessage (io.jenkins.blueocean.commons.ErrorMessage)1 HttpURLConnection (java.net.HttpURLConnection)1 MalformedURLException (java.net.MalformedURLException)1 UnknownHostException (java.net.UnknownHostException)1