hudson.model.User Java Examples

The following examples show how to use hudson.model.User. 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: TestGitRepo.java    From flaky-test-handler-plugin with Apache License 2.0 6 votes vote down vote up
public TestGitRepo(String name, File tmpDir, TaskListener listener) throws IOException, InterruptedException {
  this.name = name;
  this.listener = listener;

  envVars = new EnvVars();

  gitDir = tmpDir;
  User john = User.get(johnDoe.getName(), true);
  UserProperty johnsMailerProperty = new Mailer.UserProperty(johnDoe.getEmailAddress());
  john.addProperty(johnsMailerProperty);

  User jane = User.get(janeDoe.getName(), true);
  UserProperty janesMailerProperty = new Mailer.UserProperty(janeDoe.getEmailAddress());
  jane.addProperty(janesMailerProperty);

  // initialize the git interface.
  gitDirPath = new FilePath(gitDir);
  git = Git.with(listener, envVars).in(gitDir).getClient();

  // finally: initialize the repo
  git.init();
}
 
Example #2
Source File: MultiBranchTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void multiBranchPipelineIndex() throws Exception {
    User user = login();
    WorkflowMultiBranchProject mp = j.jenkins.createProject(WorkflowMultiBranchProject.class, "p");
    mp.getSourcesList().add(new BranchSource(new GitSCMSource(null, sampleRepo.toString(), "", "*", "", false),
            new DefaultBranchPropertyStrategy(new BranchProperty[0])));
    for (SCMSource source : mp.getSCMSources()) {
        assertEquals(mp, source.getOwner());
    }

    Map map = new RequestBuilder(baseUrl)
            .post("/organizations/jenkins/pipelines/p/runs/")
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( getCrumb( j.jenkins ) )
            .data(ImmutableMap.of())
            .status(200)
            .build(Map.class);

    assertNotNull(map);
}
 
Example #3
Source File: GitScmTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldFailOnValidation2() throws Exception {

    User user = login();
    this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId());

    Map<String,Object> resp = post("/organizations/" + getOrgName() + "/pipelines/",
            ImmutableMap.of("name", "demo",
                    "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest"
            ), 400);

    assertEquals(resp.get("code"), 400);

    List<Map> errors = (List<Map>) resp.get("errors");

    assertEquals("scmConfig", errors.get(0).get("field"));
    assertEquals("MISSING", errors.get(0).get("code"));
    assertNull(getOrgRoot().getItem("demo"));
}
 
Example #4
Source File: GitScmTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldFailOnValidation5() throws Exception {

    User user = login();
    this.jwtToken = getJwtToken(j.jenkins, user.getId(), user.getId());

    Map<String,Object> resp = post("/organizations/" + getOrgName() + "/pipelines/",
            ImmutableMap.of("name", "demo",
                    "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
                    "scmConfig", ImmutableMap.of("uri", sampleRepo.fileUrl(), "credentialId", "sdsdsd")
            ), 400);
    List<Map<String,String>> errors = (List<Map<String,String>>) resp.get("errors");

    assertEquals("scmConfig.credentialId", errors.get(0).get("field"));
    assertEquals("NOT_FOUND", errors.get(0).get("code"));
    assertNull(getOrgRoot().getItem("demo"));
}
 
Example #5
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void userCurrentTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());

    SecurityContextHolder.getContext().setAuthentication(j.jenkins.ANONYMOUS);

    Assert.assertNull(User.current());

    List<Map> l = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/pipelines/")
        .authAlice()
        .build(List.class);

    assertEquals(0, l.size());
    Assert.assertNull(User.current());
}
 
Example #6
Source File: GitPipelineCreateRequestTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void createPipeline() throws UnirestException, IOException {
    User user = login("vivek", "Vivek Pandey", "[email protected]");
    Map r = new PipelineBaseTest.RequestBuilder(baseUrl)
        .status(201)
        .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
        .crumb( crumb )
        .post("/organizations/jenkins/pipelines/")
        .data(ImmutableMap.of("name", "pipeline1",
            "$class", "io.jenkins.blueocean.blueocean_git_pipeline.GitPipelineCreateRequest",
            "scmConfig", ImmutableMap.of("id", GitScm.ID, "uri", sampleRepo.toString())))
        .build(Map.class);
    assertNotNull(r);
    assertEquals("pipeline1", r.get("name"));

    MultiBranchProject mbp = (MultiBranchProject) j.getInstance().getItem("pipeline1");
    GitSCMSource source = (GitSCMSource) mbp.getSCMSources().get(0);
    List<SCMSourceTrait> traits = source.getTraits();

    Assert.assertNotNull(SCMTrait.find(traits, BranchDiscoveryTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanAfterCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, CleanBeforeCheckoutTrait.class));
    Assert.assertNotNull(SCMTrait.find(traits, LocalBranchTrait.class));
}
 
Example #7
Source File: UserStatePreloader.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * {@inheritDoc}
 */
@Override
public String getStateJson() {

    BlueOrganization organization = Iterables.getFirst(OrganizationFactory.getInstance().list(), null);

    try {
        User currentUser = User.current();
        if (currentUser != null && organization != null) {
            return Export.toJson(new UserImpl(organization, currentUser), true);
        } else {
            return ANONYMOUS;
        }
    } catch (IOException e) {
        LOGGER.log(Level.SEVERE, "Unexpected error serializing active User object and adding to page preload state.");
        return ANONYMOUS;
    }
}
 
Example #8
Source File: HudsonPrivateSecurityRealmConfigurator.java    From configuration-as-code-plugin with MIT License 6 votes vote down vote up
private static User createAccount(HudsonPrivateSecurityRealm target, UserWithPassword user)
    throws IOException {
    User updatedUser;
    if (StringUtils.isNotBlank(user.password)) {
        if (StringUtils.startsWith(user.password, HASHED_PASSWORD_PREFIX)) {
            try {
                updatedUser = target
                    .createAccountWithHashedPassword(user.id, user.password);
            } catch (IllegalArgumentException | IOException e) {
                logger.log(Level.WARNING,
                    "Failed to create user with presumed hashed password", e);
                // fallback, just create the account as is
                updatedUser = target.createAccount(user.id, user.password);
            }
        } else {
            updatedUser = target.createAccount(user.id, user.password);
        }
    } else {
        updatedUser = User.getById(user.id, true);
    }
    return updatedUser;
}
 
Example #9
Source File: UserPublicKeyRoute.java    From blueocean-plugin with MIT License 6 votes vote down vote up
/**
 * Gets or creates the user's private Jenkins-managed key and returns the
 * public key to the user
 *
 * @return JSON response
 */
@GET
@WebMethod(name = "")
@TreeResponse
public UserKey getPublickey() {
    User authenticatedUser = User.current();
    if (authenticatedUser == null) {
        throw new ServiceException.UnauthorizedException("Not authorized");
    }
    if (!StringUtils.equals(user.getId(), authenticatedUser.getId())) {
        throw new ServiceException.ForbiddenException("Not authorized");
    }

    UserKey publicKey = UserSSHKeyManager.getPublicKey(authenticatedUser,
        UserSSHKeyManager.getOrCreate(authenticatedUser));

    return publicKey;
}
 
Example #10
Source File: GithubPipelineCreateRequestTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdMissing() throws Exception {
    // switch to bob and create a credential
    User user = login();
    createGithubCredential(user);

    String orgFolderName = "cloudbeers";
    Map resp = new RequestBuilder(baseUrl)
            .status(201)
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( this.crumb )
            .post("/organizations/"+getOrgName()+"/pipelines/")
            // since credentialId will default to 'github', it's okay to omit it in request
            .data(GithubTestUtils.buildRequestBody(GithubScm.ID, null, githubApiUrl, orgFolderName, "PR-demo"))
            .build(Map.class);
    assertNotNull(resp);
}
 
Example #11
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
private MultiBranchProject mockMbp(String credentialId, User user) {
    MultiBranchProject mbp = mock(MultiBranchProject.class);
    when(mbp.getName()).thenReturn("pipeline1");
    when(mbp.getParent()).thenReturn(j.jenkins);
    BitbucketSCMSource scmSource = mock(BitbucketSCMSource.class);
    when(scmSource.getServerUrl()).thenReturn(apiUrl);
    when(scmSource.getCredentialsId()).thenReturn(credentialId);
    when(scmSource.getRepoOwner()).thenReturn("TESTP");
    when(scmSource.getRepository()).thenReturn("pipeline-demo-test");
    when(mbp.getSCMSources()).thenReturn(Lists.<SCMSource>newArrayList(scmSource));

    //mock blueocean credential provider stuff
    BlueOceanCredentialsProvider.FolderPropertyImpl folderProperty = mock(BlueOceanCredentialsProvider.FolderPropertyImpl.class);
    DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor> properties = new DescribableList<AbstractFolderProperty<?>, AbstractFolderPropertyDescriptor>(mbp);
    properties.add(new BlueOceanCredentialsProvider.FolderPropertyImpl(
            user.getId(), credentialId,
            BlueOceanCredentialsProvider.createDomain(apiUrl)
    ));
    Domain domain = mock(Domain.class);
    when(domain.getName()).thenReturn(BitbucketServerScm.DOMAIN_NAME);
    when(folderProperty.getDomain()).thenReturn(domain);

    when(mbp.getProperties()).thenReturn(properties);
    return mbp;
}
 
Example #12
Source File: AnalyticsTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void track() {
    ImmutableMap<String, Object> props = ImmutableMap.<String, Object>of(
        "prop1", "value1",
        "prop2", 2,
        "jenkinsVersion", j.jenkins.getVersion().toString(),
        "blueoceanVersion", Jenkins.getInstance().getPlugin("blueocean-commons").getWrapper().getVersion()
    );
    analytics.track(new TrackRequest("test", props));

    Map<String, Object> expectedProps = Maps.newHashMap(props);
    expectedProps.put("jenkins", analytics.getServer());

    Assert.assertEquals("test", analytics.lastName);
    Assert.assertEquals( expectedProps, analytics.lastProps);

    // Ensure identify does not contain the username
    Assert.assertFalse(analytics.getIdentity().contains(User.current().getId()));
}
 
Example #13
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, "cloud", alice);

    StaplerRequest staplerRequest = mockStapler();

    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new BitbucketCloudScmContentProvider().getContent(staplerRequest, mbp);
    } catch (ServiceException.PreconditionRequired e) {
        assertEquals("Can't access content from Bitbucket: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #14
Source File: GithubPipelineCreateRequestTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void shouldSucceedForAuthedUserWithCredentialCreatedAndCredentialIdMissingEnterprise() throws Exception {
    // switch to bob and create a credential
    User user = login();
    createGithubEnterpriseCredential(user);

    String orgFolderName = "cloudbeers";
    Map resp = new RequestBuilder(baseUrl)
            .status(201)
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( this.crumb )
            .post("/organizations/"+getOrgName()+"/pipelines/")
            // since credentialId will default to 'github', it's okay to omit it in request
            .data(GithubTestUtils.buildRequestBody(GithubEnterpriseScm.ID, null, githubApiUrl, orgFolderName, "PR-demo"))
            .build(Map.class);
    assertNotNull(resp);
}
 
Example #15
Source File: FactsBuilder.java    From office-365-connector-plugin with Apache License 2.0 6 votes vote down vote up
public void addDevelopers() {
    if (!(run instanceof RunWithSCM)) {
        return;
    }
    RunWithSCM runWithSCM = (RunWithSCM) run;

    List<ChangeLogSet<ChangeLogSet.Entry>> sets = runWithSCM.getChangeSets();

    Set<User> authors = new HashSet<>();
    sets.stream()
            .filter(set -> set instanceof ChangeLogSet)
            .forEach(set -> set
                    .forEach(entry -> authors.add(entry.getAuthor())));

    addFact(NAME_DEVELOPERS, StringUtils.join(sortUsers(authors), ", "));
}
 
Example #16
Source File: APIHeadTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void defaultCacheHeaderTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    RequestBuilder requestBuilder = request().authAlice().get("/organizations/jenkins/users/");

    HttpResponse<List> response = requestBuilder.execute(List.class);

    List<String> list = response.getHeaders().get("Cache-Control");

    assertThat(list.get(0), containsString("no-cache"));
    assertThat(list.get(0), containsString("no-store"));
    assertThat(list.get(0), containsString("no-transform"));
}
 
Example #17
Source File: ChangeSetResourceTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void testChangeSet(){
    Reachable reachable = mock(Reachable.class);
    when(reachable.getLink()).thenReturn(new Link("/foo/bar"));
    User user = mock(User.class);
    when(user.getId()).thenReturn("vivek");
    ChangeLogSet.Entry entry = mock(ChangeLogSet.Entry.class);
    when(entry.getAuthor()).thenReturn(user);
    when(entry.getTimestamp()).thenReturn(System.currentTimeMillis());
    when(entry.getCommitId()).thenReturn("12345");
    when(entry.getMsg()).thenReturn("test changeset");
    when(entry.getAffectedPaths()).thenReturn(Collections.singleton("/foo/bar"));
    ChangeSetResource changeSetResource = new ChangeSetResource(new OrganizationImpl("testorg", mock(Folder.class)), entry, reachable);
    assertEquals(user.getId(), changeSetResource.getAuthor().getId());
    assertEquals(entry.getCommitId(), changeSetResource.getCommitId());
    assertEquals(entry.getMsg(), changeSetResource.getMsg());
}
 
Example #18
Source File: GitReadSaveRequest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@CheckForNull
StandardCredentials getCredential() {
    StandardCredentials credential = null;

    User user = User.current();
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Not authenticated");
    }

    // Get committer info and credentials
    if (GitUtils.isSshUrl(gitSource.getRemote()) || GitUtils.isLocalUnixFileUrl(gitSource.getRemote())) {
        credential = UserSSHKeyManager.getOrCreate(user);
    } else {
        String credentialId = GitScm.makeCredentialId(gitSource.getRemote());

        if (credentialId != null) {
            credential = CredentialsUtils.findCredential(credentialId,
                                                         StandardCredentials.class,
                                                         new BlueOceanDomainRequirement());
        }
    }
    return credential;
}
 
Example #19
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToMbpGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #20
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test @Ignore
public void patchMimeTest() throws Exception {
    User system = User.get("SYSTEM");

    Map response = patch("/users/"+system.getId()+"/", Collections.emptyMap());
    assertEquals(system.getId(), response.get("id"));
    assertEquals(system.getFullName(), response.get("fullName"));
}
 
Example #21
Source File: UserImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public BlueUserPermission getPermission() {
    Authentication authentication = Jenkins.getAuthentication();
    String name = authentication.getName();
    if(isAnonymous(name)){
        return null;
    }

    User loggedInUser = User.get(name, false, Collections.EMPTY_MAP);
    if(loggedInUser == null){
        return null;
    }

    // If this user is not logged in, we do not show it's permissions
    // XXX: This is done to avoid impersonation which has performance
    //      implications, e.g. github oauth plugin might do a network
    //      round trip to fetch user and authorizations
    if(!loggedInUser.getId().equals(user.getId())){
        return null;
    }

    return new BlueUserPermission() {
        @Override
        public boolean isAdministration() {
            return isAdmin();
        }

        @Override
        public Map<String, Boolean> getPipelinePermission() {
            return UserImpl.this.getPipelinePermissions();
        }

        @Override
        public Map<String, Boolean> getCredentialPermission() {
            return UserImpl.this.getCredentialPermissions();
        }
    };
}
 
Example #22
Source File: AbstractBitbucketScm.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * 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(),
                    ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
        } else {
            CredentialsUtils.updateCredentialsInUserStore(
                    bbCredentials, credential, authenticatedUser, getDomainId(),
                    ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
        }

        return createResponse(credential.getId());
    }catch (IOException e){
        throw new ServiceException.UnexpectedErrorException(e.getMessage());
    }
}
 
Example #23
Source File: GitReadSaveTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void bareRepoReadWriteNoEmail() throws Exception {
    if (!OsUtils.isUNIX()) {
        return; // can't really run this on windows
    }
    User user = login("bob", "Bob Smith", null);

    startSSH(user);
    String userHostPort = "[email protected]:" + sshd.getPort();
    String remote = "ssh://" + userHostPort + "" + repoForSSH.getRoot().getCanonicalPath() + "/.git";
    testGitReadWrite(GitReadSaveService.ReadSaveType.CACHE_BARE, remote, repoForSSH, masterPipelineScript, user);
}
 
Example #24
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToOrgFolderGHEShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubEnterpriseCredential(alice);


    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n")
            .branch("test1").message("another commit").owner("cloudbeers").path("Jankinsfile").repo("PR-demo").sha("e23b8ef5c2c4244889bf94db6c05cc08ea138aef").build();

    when(staplerRequest.bindJSON(Mockito.eq(GithubScmSaveFileRequest.class), Mockito.any(JSONObject.class))).thenReturn(new GithubScmSaveFileRequest(content));

    MultiBranchProject mbp = mockMbp(aliceCredentialId, user, GithubEnterpriseScm.DOMAIN_NAME);

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"first commit\",\n" +
            "    \"path\" : \"Jenkinsfile\",\n" +
            "    \"branch\" : \"test1\",\n" +
            "    \"repo\" : \"PR-demo\",\n" +
            "    \"sha\" : \"e23b8ef5c2c4244889bf94db6c05cc08ea138aef\",\n" +
            "    \"base64Data\" : "+"\"c2xlZXAgMTUKbm9kZSB7CiAgY2hlY2tvdXQgc2NtCiAgc2ggJ2xzIC1sJwp9\\nCnNsZWVwIDE1Cg==\\n\""+
            "  }\n" +
            "}";

    when(staplerRequest.getReader()).thenReturn(new BufferedReader(new StringReader(request), request.length()));
    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().saveContent(staplerRequest, mbp);
    }catch (ServiceException.PreconditionRequired e){
        assertEquals("Can't access content from github: no credential found", e.getMessage());
        return;
    }
    fail("Should have failed with PreConditionException");
}
 
Example #25
Source File: UserSSHKeyManager.java    From blueocean-plugin with MIT License 5 votes vote down vote up
/**
 * Gets the user's CredentialStore
 * @param user user to find a store for
 * @return the credential store or null if not found
 */
private static @CheckForNull CredentialsStore getUserStore(User user){
    for(CredentialsStore s : CredentialsProvider.lookupStores(user)) {
        if(s.hasPermission(CredentialsProvider.CREATE) && s.hasPermission(CredentialsProvider.UPDATE)){
            return s;
        }
    }
    return null;
}
 
Example #26
Source File: GitHubPRRepositoryTest.java    From github-integration-plugin with MIT License 5 votes vote down vote up
private void hasPermissionExpectation(Permission permission, boolean isAllowed) {
    PowerMockito.mockStatic(Jenkins.class);
    when(Jenkins.getInstance()).thenReturn(instance);
    when(instance.hasPermission(permission)).thenReturn(isAllowed);
    PowerMockito.mockStatic(User.class);
    when(User.current()).thenReturn(user);
}
 
Example #27
Source File: JwtTokenVerifierImpl.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public JwtAuthentication(String subject) {
    User user = User.get(subject, false, Collections.emptyMap());
    if (user == null) {
        throw new ServiceException.UnauthorizedException("Invalid JWT token: subject " + subject + " not found");
    }
    //TODO: UserDetails call is expensive, encode it in token and create UserDetails from it
    UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(user.getId());
    this.grantedAuthorities = d.getAuthorities();
    this.name = subject;
    super.setAuthenticated(true);
}
 
Example #28
Source File: GithubMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
protected String createGithubCredential(User user) throws UnirestException {
    Map r = new RequestBuilder(baseUrl)
            .data(ImmutableMap.of("accessToken", accessToken))
            .status(200)
            .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
            .crumb( this.crumb )
            .put("/organizations/" + getOrgName() + "/scm/github/validate/?apiUrl="+githubApiUrl)
            .build(Map.class);
    String credentialId = (String) r.get("credentialId");
    assertEquals(GithubScm.ID, credentialId);
    return credentialId;
}
 
Example #29
Source File: GitScmTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void shouldCreateCredentialsWithDefaultId() throws Exception {
    User user = login();

    String scmPath = "/organizations/" + getOrgName() + "/scm/git/";

    // First create a credential
    String scmValidatePath = scmPath + "validate";

    // We're relying on github letting you do a git-ls for repos with bad creds so long as they're public
    Map params = ImmutableMap.of(
        "userName", "someguy",
        "password", "password",
        "repositoryUrl", HTTPS_GITHUB_PUBLIC
    );

    Map resp = new RequestBuilder(baseUrl)
        .status(200)
        .jwtToken(getJwtToken(j.jenkins,user.getId(), user.getId()))
        .crumb( crumb )
        .data(params)
        .put(scmValidatePath)
        .build(Map.class);

    assertEquals("ok", resp.get("status"));

    // Now get the default credentialId

    String repoPath = scmPath + "?repositoryUrl=" + HTTPS_GITHUB_PUBLIC;

    Map resp2 = new RequestBuilder(baseUrl)
        .status(200)
        .jwtToken(getJwtToken(j.jenkins,user.getId(), user.getId()))
        .crumb( crumb )
        .get(repoPath)
        .build(Map.class);

    assertEquals("git:" + HTTPS_GITHUB_PUBLIC_HASH, resp2.get("credentialId"));
}
 
Example #30
Source File: BitbucketWireMockBase.java    From blueocean-plugin with MIT License 5 votes vote down vote up
protected String createCredential(String scmId, String apiMode, User user) throws IOException, UnirestException {

        RequestBuilder builder = new RequestBuilder(baseUrl)
                .status(200)
                .jwtToken(getJwtToken(j.jenkins, user.getId(), user.getId()))
                .put("/organizations/jenkins/scm/"+ scmId+"/validate/")
                .data(ImmutableMap.of("apiUrl",apiUrl, "userName", getUserName(), "password",getPassword()));

        Map r = builder.build(Map.class);

        assertNotNull(r);
        String credentialId = (String) r.get("credentialId");
        assertNotNull(credentialId);
        return credentialId;
    }