hudson.tasks.Mailer Java Examples

The following examples show how to use hudson.tasks.Mailer. 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: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForMbpShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler(GithubEnterpriseScm.ID);

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

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(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 #2
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 #3
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForMbpGHEShouldFail() 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);

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

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(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 #4
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForOrgFolderGHEShouldFail() 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);

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

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(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 #5
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void unauthorizedAccessToContentForOrgFolderShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler();

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

    try {
        //Bob trying to access content but his credential is not setup so should fail
        new GithubScmContentProvider().getContent(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 #6
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Test
public void getAuthenticatedUserShouldFail() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("[email protected]"));

    hudson.model.User user1 = User.get("bob");
    user1.setFullName("Bob Cooper");
    user1.addProperty(new Mailer.UserProperty("[email protected]"));

    Map u = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/user/")
        .status(404)
        .build(Map.class); //sends jwt token for anonymous user
}
 
Example #7
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 #8
Source File: UserImpl.java    From blueocean-plugin with MIT License 6 votes vote down vote up
@Override
public String getEmail() {
    String name = Jenkins.getAuthentication().getName();
    if(isAnonymous(name)){
        return null;
    }else{
        User user = User.get(name, false, Collections.EMPTY_MAP);
        if(user == null){
            return null;
        }
        if (!user.hasPermission(Jenkins.ADMINISTER)) return null;
    }

    Mailer.UserProperty p = user.getProperty(Mailer.UserProperty.class);
    return p != null ? p.getAddress() : null;
}
 
Example #9
Source File: BitbucketServerScmContentProviderTest.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(BitbucketServerScm.ID, 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 BitbucketServerScmContentProvider().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 #10
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 #11
Source File: MailerTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Test
@ConfiguredWithReadme("mailer/README.md")
public void configure_mailer() throws Exception {
    final Jenkins jenkins = Jenkins.get();
    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
    assertEquals("smtp.acme.org", descriptor.getSmtpHost() );
}
 
Example #12
Source File: BitbucketServerScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketServerScm.ID, alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K")
            .branch("master").message("new commit").owner("TESTP").path("README.md").repo("pipeline-demo-test").build();

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

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"new commit\",\n" +
            "    \"path\" : \"README.md\",\n" +
            "    \"branch\" : \"master\",\n" +
            "    \"repo\" : \"pipeline-demo-test\",\n" +
            "    \"base64Data\" : " + "\"bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K\"" +
            "  }\n" +
            "}";

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

    try {
        new BitbucketServerScmContentProvider().saveContent(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 #13
Source File: OicSecurityRealm.java    From oic-auth-plugin with MIT License 5 votes vote down vote up
private UsernamePasswordAuthenticationToken loginAndSetUserData(String userName, IdToken idToken, GenericJson userInfo) throws IOException {

        GrantedAuthority[] grantedAuthorities = determineAuthorities(idToken, userInfo);
        if(LOGGER.isLoggable(Level.FINEST)) {
		    StringBuilder grantedAuthoritiesAsString = new StringBuilder("(");
		    for(GrantedAuthority grantedAuthority : grantedAuthorities) {
		        grantedAuthoritiesAsString.append(" ").append(grantedAuthority.getAuthority());
            }
            grantedAuthoritiesAsString.append(" )");
		    LOGGER.finest("GrantedAuthorities:" + grantedAuthoritiesAsString);
        }

        UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userName, "", grantedAuthorities);

        SecurityContextHolder.getContext().setAuthentication(token);

        User user = User.get(token.getName());
        // Store the list of groups in a OicUserProperty so it can be retrieved later for the UserDetails object.
        user.addProperty(new OicUserProperty(userName, grantedAuthorities));

        if(emailFieldName!=null) {
	        String email = userInfo == null ? getField(idToken, emailFieldName) : (String) getField(userInfo, emailFieldName);
	        if (email != null) {
	            user.addProperty(new Mailer.UserProperty(email));
	        }
        }

        if(fullNameFieldName!=null) {
		    String fullName = userInfo == null ? getField(idToken, fullNameFieldName) : (String) getField(userInfo, fullNameFieldName);
		    if (fullName != null) {
		        user.setFullName(fullName);
		    }
        }

        OicUserDetails userDetails = new OicUserDetails(userName, grantedAuthorities);
        SecurityListener.fireAuthenticated(userDetails);

        return token;
    }
 
Example #14
Source File: PipelineScmTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Override
public void setup() throws Exception {
    super.setup();
    this.bob = login();
    this.alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));
}
 
Example #15
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 #16
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToMbpShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);

    StaplerRequest staplerRequest = mockStapler();

    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, GithubScm.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 #17
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 #18
Source File: GithubScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentToOrgFolderShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createGithubCredential(alice);


    StaplerRequest staplerRequest = mockStapler();

    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, GithubScm.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 #19
Source File: RoundTripMailerTest.java    From configuration-as-code-plugin with MIT License 5 votes vote down vote up
@Override
protected void assertConfiguredAsExpected(RestartableJenkinsRule j, String configContent) {
    final Jenkins jenkins = Jenkins.get();
    final Mailer.DescriptorImpl descriptor = (Mailer.DescriptorImpl) jenkins.getDescriptor(Mailer.class);
    assertEquals("4441", descriptor.getSmtpPort());
    assertEquals("[email protected]", descriptor.getReplyToAddress());
}
 
Example #20
Source File: BitbucketCloudScmContentProviderTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void unauthorizedSaveContentShouldFail() throws UnirestException, IOException {
    User alice = User.get("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    String aliceCredentialId = createCredential(BitbucketCloudScm.ID, alice);
    StaplerRequest staplerRequest = mockStapler();
    MultiBranchProject mbp = mockMbp(aliceCredentialId, alice);

    GitContent content = new GitContent.Builder().autoCreateBranch(true).base64Data("bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K")
            .branch("master").message("new commit").owner("TESTP").path("README.md").repo("pipeline-demo-test").build();

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

    String request = "{\n" +
            "  \"content\" : {\n" +
            "    \"message\" : \"new commit\",\n" +
            "    \"path\" : \"README.md\",\n" +
            "    \"branch\" : \"master\",\n" +
            "    \"repo\" : \"pipeline-demo-test\",\n" +
            "    \"base64Data\" : " + "\"bm9kZXsKICBlY2hvICdoZWxsbyB3b3JsZCEnCn0K\"" +
            "  }\n" +
            "}";

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

    try {
        new BitbucketCloudScmContentProvider().saveContent(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 #21
Source File: OrganizationApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void organizationUsers() 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]"));

    List users = request().authAlice().get("/organizations/jenkins/users/").build(List.class);

    Assert.assertEquals(users.size(), 1);
    Map aliceMap = (Map) users.get(0);
    Assert.assertEquals(aliceMap.get("id"), "alice");
    Assert.assertEquals(aliceMap.get("fullName"), "Alice Cooper");
    Assert.assertEquals(aliceMap.get("email"), "[email protected]");
}
 
Example #22
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getAuthenticatedUser() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User user = User.get("alice");
    user.setFullName("Alice Cooper");
    user.addProperty(new Mailer.UserProperty("[email protected]"));

    // String token = getJwtToken(j.jenkins,"alice", "alice");

    Map u = new RequestBuilder(baseUrl)
        .get("/organizations/jenkins/user/")
        .authAlice()
        .status(200)
        .build(Map.class);

    assertEquals(user.getFullName(), u.get("fullName"));
    assertEquals("[email protected]", u.get("email"));
    assertEquals(user.getId(), u.get("id"));
    Map permission = (Map) u.get("permission");
    assertNotNull(permission);
    assertTrue((Boolean) permission.get("administrator"));
    Map pipelinePerm = (Map) permission.get("pipeline");
    assertEquals(true, pipelinePerm.get("start"));
    assertEquals(true, pipelinePerm.get("create"));
    assertEquals(true, pipelinePerm.get("read"));
    assertEquals(true, pipelinePerm.get("stop"));
    assertEquals(true, pipelinePerm.get("configure"));

    Map credentialPerm = (Map) permission.get("credential");
    assertEquals(true, credentialPerm.get("create"));
    assertEquals(true, credentialPerm.get("view"));
    assertEquals(true, credentialPerm.get("update"));
    assertEquals(true, credentialPerm.get("manageDomains"));
    assertEquals(true, credentialPerm.get("delete"));
}
 
Example #23
Source File: APIHeadTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
public void overrideCacheHeaderTest() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    hudson.model.User alice = j.jenkins.getUser("alice");
    alice.setFullName("Alice Cooper");
    alice.addProperty(new Mailer.UserProperty("[email protected]"));

    RequestBuilder requestBuilder = request().authAlice().get("/test/");

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

    List<String> list = response.getHeaders().get("Cache-Control");
    assertThat(list.get(0), containsString("max-age=10"));

}
 
Example #24
Source File: ProfileApiTest.java    From blueocean-plugin with MIT License 5 votes vote down vote up
@Test
public void getUserDetailsTest() 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]"));

    hudson.model.User bob = User.get("bob");

    bob.setFullName("Bob Smith");
    bob.addProperty(new Mailer.UserProperty("[email protected]"));

    //Call is made as anonymous user, email should be null
    Map response = get("/users/"+alice.getId());
    assertEquals(alice.getId(), response.get("id"));
    assertEquals(alice.getFullName(), response.get("fullName"));
    Assert.assertNull(response.get("email"));

    //make a request on bob's behalf to get alice's user details, should get null email
    Map r = new RequestBuilder(baseUrl)
        .status(200)
        .auth("bob", "bob")
        .get("/users/"+alice.getId()).build(Map.class);

    assertEquals(alice.getId(), r.get("id"));
    assertEquals(alice.getFullName(), r.get("fullName"));
    Assert.assertTrue(bob.hasPermission(Jenkins.ADMINISTER));
    //bob is admin so can see alice email
    assertEquals("[email protected]",r.get("email"));

    r = new RequestBuilder(baseUrl)
        .status(200)
        .authAlice()
        .get("/users/"+alice.getId()).build(Map.class);

    assertEquals(alice.getId(), r.get("id"));
    assertEquals(alice.getFullName(), r.get("fullName"));
    assertEquals("[email protected]",r.get("email"));
}
 
Example #25
Source File: Config.java    From repairnator with MIT License 4 votes vote down vote up
public String getSmtpUsername() {
	if (Mailer.descriptor().getAuthentication() != null) {
		return Mailer.descriptor().getAuthentication().getUsername();
	}
	return null;
}
 
Example #26
Source File: PluginTest.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
@Test public void testNestedFieldLookupFromUserInfoEndpoint() throws Exception {
    wireMockRule.resetAll();

    KeyPair keyPair = createKeyPair();

    wireMockRule.stubFor(get(urlPathEqualTo("/authorization")).willReturn(
        aResponse()
            .withStatus(302)
            .withHeader("Content-Type", "text/html; charset=utf-8")
            .withHeader("Location", jenkins.getRootUrl()+"securityRealm/finishLogin?state=state&code=code")
            .withBody("")
    ));
    wireMockRule.stubFor(post(urlPathEqualTo("/token")).willReturn(
        aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{" +
                "\"id_token\": \""+createIdToken(keyPair.getPrivate(),Collections.<String,Object>emptyMap())+"\"," +
                "\"access_token\":\"AcCeSs_ToKeN\"," +
                "\"token_type\":\"example\"," +
                "\"expires_in\":3600," +
                "\"refresh_token\":\"ReFrEsH_ToKeN\"," +
                "\"example_parameter\":\"example_value\"" +
                "}")
    ));
    wireMockRule.stubFor(get(urlPathEqualTo("/userinfo")).willReturn(
        aResponse()
            .withHeader("Content-Type", "application/json")
            .withBody("{\n" +
                "   \"sub\": \""+TEST_USER_USERNAME+"\",\n" +
                "   \""+FULL_NAME_FIELD+"\": \""+TEST_USER_FULL_NAME+"\",\n" +
                "   \"nested\": {\n" +
                "     \"email\": \""+TEST_USER_EMAIL_ADDRESS+"\",\n" +
                "     \"groups\": "+toJsonArray(TEST_USER_GROUPS)+"\n" +
                "   }\n" +
                "  }")
    ));


    jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo", "nested.email", "nested.groups"));

    assertEquals("Shouldn't be authenticated", getAuthentication().getPrincipal(), Jenkins.ANONYMOUS.getPrincipal());

    webClient.goTo(jenkins.getSecurityRealm().getLoginUrl());

    Authentication authentication = getAuthentication();
    assertEquals("Should be logged-in as "+ TEST_USER_USERNAME, authentication.getPrincipal(), TEST_USER_USERNAME);
    User user = User.get(String.valueOf(authentication.getPrincipal()));
    assertEquals("Full name should be "+TEST_USER_FULL_NAME, TEST_USER_FULL_NAME, user.getFullName());
    assertEquals("Email should be "+ TEST_USER_EMAIL_ADDRESS, TEST_USER_EMAIL_ADDRESS, user.getProperty(Mailer.UserProperty.class).getAddress());
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[0], user.getAuthorities().contains(TEST_USER_GROUPS[0]));
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[1], user.getAuthorities().contains(TEST_USER_GROUPS[1]));
}
 
Example #27
Source File: PluginTest.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
@Test public void testNestedFieldLookup() throws Exception {
    KeyPair keyPair = createKeyPair();

    wireMockRule.stubFor(get(urlPathEqualTo("/authorization")).willReturn(
        aResponse()
            .withStatus(302)
            .withHeader("Content-Type", "text/html; charset=utf-8")
            .withHeader("Location", jenkins.getRootUrl()+"securityRealm/finishLogin?state=state&code=code")
            .withBody("")
    ));
    Map<String, Object> nested = new HashMap<>();
    nested.put("email", TEST_USER_EMAIL_ADDRESS);
    nested.put("groups", TEST_USER_GROUPS);
    Map<String, Object> keyValues = new HashMap<>();
    keyValues.put("nested", nested);
    keyValues.put(FULL_NAME_FIELD, TEST_USER_FULL_NAME);

    wireMockRule.stubFor(post(urlPathEqualTo("/token")).willReturn(
        aResponse()
            .withHeader("Content-Type", "text/html; charset=utf-8")
            .withBody("{" +
                "\"id_token\": \""+createIdToken(keyPair.getPrivate(), keyValues)+"\"," +
                "\"access_token\":\"AcCeSs_ToKeN\"," +
                "\"token_type\":\"example\"," +
                "\"expires_in\":3600," +
                "\"refresh_token\":\"ReFrEsH_ToKeN\"," +
                "\"example_parameter\":\"example_value\"" +
                "}")
    ));


    jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, "nested.email", "nested.groups"));

    assertEquals("Shouldn't be authenticated", getAuthentication().getPrincipal(), Jenkins.ANONYMOUS.getPrincipal());

    webClient.goTo(jenkins.getSecurityRealm().getLoginUrl());

    Authentication authentication = getAuthentication();
    assertEquals("Should be logged-in as "+ TEST_USER_USERNAME, authentication.getPrincipal(), TEST_USER_USERNAME);
    User user = User.get(String.valueOf(authentication.getPrincipal()));
    assertEquals("Full name should be "+TEST_USER_FULL_NAME, TEST_USER_FULL_NAME, user.getFullName());
    assertEquals("Email should be "+ TEST_USER_EMAIL_ADDRESS, TEST_USER_EMAIL_ADDRESS, user.getProperty(Mailer.UserProperty.class).getAddress());
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[0], user.getAuthorities().contains(TEST_USER_GROUPS[0]));
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[1], user.getAuthorities().contains(TEST_USER_GROUPS[1]));
}
 
Example #28
Source File: PluginTest.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
@Test public void testLoginUsingUserInfoEndpoint() throws Exception {
    wireMockRule.resetAll();

    KeyPair keyPair = createKeyPair();

    wireMockRule.stubFor(get(urlPathEqualTo("/authorization")).willReturn(
            aResponse()
                    .withStatus(302)
                    .withHeader("Content-Type", "text/html; charset=utf-8")
                    .withHeader("Location", jenkins.getRootUrl()+"securityRealm/finishLogin?state=state&code=code")
                    .withBody("")
    ));
    wireMockRule.stubFor(post(urlPathEqualTo("/token")).willReturn(
            aResponse()
                    .withHeader("Content-Type", "application/json")
                    .withBody("{" +
                            "\"id_token\": \""+createIdToken(keyPair.getPrivate(),Collections.<String,Object>emptyMap())+"\"," +
                            "\"access_token\":\"AcCeSs_ToKeN\"," +
                            "\"token_type\":\"example\"," +
                            "\"expires_in\":3600," +
                            "\"refresh_token\":\"ReFrEsH_ToKeN\"," +
                            "\"example_parameter\":\"example_value\"" +
                            "}")
    ));
    wireMockRule.stubFor(get(urlPathEqualTo("/userinfo")).willReturn(
            aResponse()
                .withHeader("Content-Type", "application/json")
                .withBody("{\n" +
                        "   \"sub\": \""+TEST_USER_USERNAME+"\",\n" +
                        "   \""+FULL_NAME_FIELD+"\": \""+TEST_USER_FULL_NAME+"\",\n" +
                        "   \""+EMAIL_FIELD+"\": \""+TEST_USER_EMAIL_ADDRESS+"\",\n" +
                        "   \""+GROUPS_FIELD+"\": "+toJsonArray(TEST_USER_GROUPS)+"\n" +
                        "  }")
    ));


    jenkins.setSecurityRealm(new TestRealm(wireMockRule, "http://localhost:" + wireMockRule.port() + "/userinfo"));

    assertEquals("Shouldn't be authenticated", getAuthentication().getPrincipal(), Jenkins.ANONYMOUS.getPrincipal());

    webClient.goTo(jenkins.getSecurityRealm().getLoginUrl());

    Authentication authentication = getAuthentication();
    assertEquals("Should be logged-in as "+ TEST_USER_USERNAME, authentication.getPrincipal(), TEST_USER_USERNAME);
    User user = User.get(String.valueOf(authentication.getPrincipal()));
    assertEquals("Full name should be "+TEST_USER_FULL_NAME, TEST_USER_FULL_NAME, user.getFullName());
    assertEquals("Email should be "+ TEST_USER_EMAIL_ADDRESS, TEST_USER_EMAIL_ADDRESS, user.getProperty(Mailer.UserProperty.class).getAddress());
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[0], user.getAuthorities().contains(TEST_USER_GROUPS[0]));
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[1], user.getAuthorities().contains(TEST_USER_GROUPS[1]));
}
 
Example #29
Source File: PluginTest.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
@Test public void testLoginWithMinimalConfiguration() throws Exception {
    KeyPair keyPair = createKeyPair();

    wireMockRule.stubFor(get(urlPathEqualTo("/authorization")).willReturn(
        aResponse()
                .withStatus(302)
                .withHeader("Content-Type", "text/html; charset=utf-8")
                .withHeader("Location", jenkins.getRootUrl()+"securityRealm/finishLogin?state=state&code=code")
                .withBody("")
    ));
    Map<String, Object> keyValues = new HashMap<>();
    keyValues.put(EMAIL_FIELD, TEST_USER_EMAIL_ADDRESS);
    keyValues.put(FULL_NAME_FIELD, TEST_USER_FULL_NAME);
    keyValues.put(GROUPS_FIELD, TEST_USER_GROUPS);

    wireMockRule.stubFor(post(urlPathEqualTo("/token")).willReturn(
        aResponse()
            .withHeader("Content-Type", "text/html; charset=utf-8")
            .withBody("{" +
                        "\"id_token\": \""+createIdToken(keyPair.getPrivate(), keyValues)+"\"," +
                        "\"access_token\":\"AcCeSs_ToKeN\"," +
                        "\"token_type\":\"example\"," +
                        "\"expires_in\":3600," +
                        "\"refresh_token\":\"ReFrEsH_ToKeN\"," +
                        "\"example_parameter\":\"example_value\"" +
                    "}")
    ));


    jenkins.setSecurityRealm(new TestRealm(wireMockRule, null, null, null));

    assertEquals("Shouldn't be authenticated", getAuthentication().getPrincipal(), Jenkins.ANONYMOUS.getPrincipal());

    webClient.goTo(jenkins.getSecurityRealm().getLoginUrl());

    Authentication authentication = getAuthentication();
    assertEquals("Should be logged-in as "+ TEST_USER_USERNAME, TEST_USER_USERNAME, authentication.getPrincipal());
    User user = User.get(String.valueOf(authentication.getPrincipal()));
    assertEquals("Full name should be "+TEST_USER_FULL_NAME, TEST_USER_FULL_NAME, user.getFullName());
    assertEquals("Email should be null"+ TEST_USER_EMAIL_ADDRESS, null, user.getProperty(Mailer.UserProperty.class).getAddress());
    assertTrue("User should be not be part of any group", user.getAuthorities().isEmpty());
}
 
Example #30
Source File: PluginTest.java    From oic-auth-plugin with MIT License 4 votes vote down vote up
@Test public void testLogin() throws Exception {
    KeyPair keyPair = createKeyPair();

    wireMockRule.stubFor(get(urlPathEqualTo("/authorization")).willReturn(
        aResponse()
                .withStatus(302)
                .withHeader("Content-Type", "text/html; charset=utf-8")
                .withHeader("Location", jenkins.getRootUrl()+"securityRealm/finishLogin?state=state&code=code")
                .withBody("")
    ));
    Map<String, Object> keyValues = new HashMap<>();
    keyValues.put(EMAIL_FIELD, TEST_USER_EMAIL_ADDRESS);
    keyValues.put(FULL_NAME_FIELD, TEST_USER_FULL_NAME);
    keyValues.put(GROUPS_FIELD, TEST_USER_GROUPS);

    wireMockRule.stubFor(post(urlPathEqualTo("/token")).willReturn(
        aResponse()
            .withHeader("Content-Type", "text/html; charset=utf-8")
            .withBody("{" +
                        "\"id_token\": \""+createIdToken(keyPair.getPrivate(), keyValues)+"\"," +
                        "\"access_token\":\"AcCeSs_ToKeN\"," +
                        "\"token_type\":\"example\"," +
                        "\"expires_in\":3600," +
                        "\"refresh_token\":\"ReFrEsH_ToKeN\"," +
                        "\"example_parameter\":\"example_value\"" +
                    "}")
    ));


    jenkins.setSecurityRealm(new TestRealm(wireMockRule));

    assertEquals("Shouldn't be authenticated", getAuthentication().getPrincipal(), Jenkins.ANONYMOUS.getPrincipal());

    webClient.goTo(jenkins.getSecurityRealm().getLoginUrl());

    Authentication authentication = getAuthentication();
    assertEquals("Should be logged-in as "+ TEST_USER_USERNAME, TEST_USER_USERNAME, authentication.getPrincipal());
    User user = User.get(String.valueOf(authentication.getPrincipal()));
    assertEquals("Full name should be "+TEST_USER_FULL_NAME, TEST_USER_FULL_NAME, user.getFullName());
    assertEquals("Email should be "+ TEST_USER_EMAIL_ADDRESS, TEST_USER_EMAIL_ADDRESS, user.getProperty(Mailer.UserProperty.class).getAddress());
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[0], user.getAuthorities().contains(TEST_USER_GROUPS[0]));
    assertTrue("User should be part of group "+ TEST_USER_GROUPS[1], user.getAuthorities().contains(TEST_USER_GROUPS[1]));
}