下面列出了hudson.model.UserProperty#hudson.tasks.Mailer 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@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");
}
@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");
}
@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;
}
@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"));
}
@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
}
@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");
}
@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");
}
@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");
}
@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");
}
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();
}
@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());
}
@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() );
}
@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");
}
@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");
}
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"));
}
@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("alice[email protected]",r.get("email"));
}
@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"));
}
@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]");
}
@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");
}
@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");
}
@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");
}
@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");
}
@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]"));
}
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;
}
@Test
@ConfiguredWithCode("jenkins/jenkins.yaml")
public void configure_demo_yaml() throws Exception {
final Jenkins jenkins = Jenkins.get();
assertEquals("Jenkins configured automatically by Jenkins Configuration as Code plugin\n\n", jenkins.getSystemMessage());
assertEquals(5, jenkins.getNumExecutors());
assertEquals(2, jenkins.getScmCheckoutRetryCount());
assertEquals(Mode.NORMAL, jenkins.getMode());
assertEquals("https://ci.example.com/", jenkins.getRootUrl());
final FullControlOnceLoggedInAuthorizationStrategy strategy = (FullControlOnceLoggedInAuthorizationStrategy) jenkins.getAuthorizationStrategy();
assertFalse(strategy.isAllowAnonymousRead());
final DockerCloud docker = DockerCloud.getCloudByName("docker");
assertNotNull(docker);
assertNotNull(docker.getDockerApi());
assertNotNull(docker.getDockerApi().getDockerHost());
assertEquals("unix:///var/run/docker.sock", docker.getDockerApi().getDockerHost().getUri());
final GitTool.DescriptorImpl gitTool = (GitTool.DescriptorImpl) jenkins.getDescriptor(GitTool.class);
assertEquals(1, gitTool.getInstallations().length);
assertEquals(1, GlobalLibraries.get().getLibraries().size());
final LibraryConfiguration library = GlobalLibraries.get().getLibraries().get(0);
assertEquals("awesome-lib", library.getName());
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() );
final ArtifactoryBuilder.DescriptorImpl artifactory = (ArtifactoryBuilder.DescriptorImpl) jenkins.getDescriptor(ArtifactoryBuilder.class);
assertTrue(artifactory.getUseCredentialsPlugin());
final List<ArtifactoryServer> actifactoryServers = artifactory.getArtifactoryServers();
assertThat(actifactoryServers, hasSize(1));
assertThat(actifactoryServers.get(0).getName(), is(equalTo("artifactory")));
assertThat(actifactoryServers.get(0).getUrl(), is(equalTo("http://acme.com/artifactory")));
assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getUsername(), is(equalTo("artifactory_user")));
assertThat(actifactoryServers.get(0).getResolverCredentialsConfig().getPassword(), is(equalTo("password123")));
}
@Override
public JwtToken getToken(@Nullable @QueryParameter("expiryTimeInMins") Integer expiryTimeInMins, @Nullable @QueryParameter("maxExpiryTimeInMins") Integer maxExpiryTimeInMins) {
long expiryTime= Long.getLong("EXPIRY_TIME_IN_MINS",DEFAULT_EXPIRY_IN_SEC);
int maxExpiryTime = Integer.getInteger("MAX_EXPIRY_TIME_IN_MINS",DEFAULT_MAX_EXPIRY_TIME_IN_MIN);
if(maxExpiryTimeInMins != null){
maxExpiryTime = maxExpiryTimeInMins;
}
if(expiryTimeInMins != null){
if(expiryTimeInMins > maxExpiryTime) {
throw new ServiceException.BadRequestException(
String.format("expiryTimeInMins %s can't be greater than %s", expiryTimeInMins, maxExpiryTime));
}
expiryTime = expiryTimeInMins * 60;
}
Authentication authentication = Jenkins.getAuthentication();
String userId = authentication.getName();
User user = User.get(userId, false, Collections.emptyMap());
String email = null;
String fullName = null;
if(user != null) {
fullName = user.getFullName();
userId = user.getId();
Mailer.UserProperty p = user.getProperty(Mailer.UserProperty.class);
if(p!=null)
email = p.getAddress();
}
Plugin plugin = Jenkins.getInstance().getPlugin("blueocean-jwt");
String issuer = "blueocean-jwt:"+ ((plugin!=null) ? plugin.getWrapper().getVersion() : "");
JwtToken jwtToken = new JwtToken();
jwtToken.claim.put("jti", UUID.randomUUID().toString().replace("-",""));
jwtToken.claim.put("iss", issuer);
jwtToken.claim.put("sub", userId);
jwtToken.claim.put("name", fullName);
long currentTime = System.currentTimeMillis()/1000;
jwtToken.claim.put("iat", currentTime);
jwtToken.claim.put("exp", currentTime+expiryTime);
jwtToken.claim.put("nbf", currentTime - DEFAULT_NOT_BEFORE_IN_SEC);
//set claim
JSONObject context = new JSONObject();
JSONObject userObject = new JSONObject();
userObject.put("id", userId);
userObject.put("fullName", fullName);
userObject.put("email", email);
JwtAuthenticationStore authenticationStore = getJwtStore(authentication);
authenticationStore.store(authentication, context);
context.put("user", userObject);
jwtToken.claim.put("context", context);
return jwtToken;
}
@Test
public void testPermissionOfOtherUser() throws IOException {
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 Cooper");
bob.addProperty(new Mailer.UserProperty("[email protected]"));
UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());
SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));
Assert.assertNull(new UserImpl(Iterables.getFirst(OrganizationFactory.getInstance().list(), null), alice).getPermission());
}
@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));
GHUser user = GithubScm.getMappingObjectReader().forType(GHUser.class).readValue(data);
if(user.getEmail() != null){
Mailer.UserProperty p = authenticatedUser.getProperty(Mailer.UserProperty.class);
//XXX: If there is already email address of this user, should we update it with
// 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(),
ImmutableList.<DomainSpecification>of(new BlueOceanDomainSpecification()));
}else{
CredentialsUtils.updateCredentialsInUserStore(
githubCredential, credential, authenticatedUser, getCredentialDomainName(),
ImmutableList.<DomainSpecification>of(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());
}
}
protected void validateAndCreate(String accessToken) throws Exception {
Mailer.UserProperty userProperty = mock(Mailer.UserProperty.class);
when(userProperty.getAddress()).thenReturn("[email protected]");
JSONObject req = new JSONObject().element("accessToken", accessToken);
GithubScm githubScm = new GithubScm(new Reachable() {
@Override
public Link getLink() {
return new Link("/blue/organizations/jenkins/scm/");
}
});
mockCredentials("joe", accessToken, githubScm.getId(), GithubScm.DOMAIN_NAME);
mockStatic(HttpRequest.class);
HttpRequest httpRequestMock = mock(HttpRequest.class);
ArgumentCaptor<String> urlStringCaptor = ArgumentCaptor.forClass(String.class);
when(HttpRequest.get(urlStringCaptor.capture())).thenReturn(httpRequestMock);
ArgumentCaptor<String> tokenCaptor = ArgumentCaptor.forClass(String.class);
when(httpRequestMock.withAuthorizationToken(tokenCaptor.capture())).thenReturn(httpRequestMock);
HttpURLConnection httpURLConnectionMock = mock(HttpURLConnection.class);
doNothing().when(httpURLConnectionMock).connect();
when(httpRequestMock.connect()).thenReturn(httpURLConnectionMock);
when(httpURLConnectionMock.getHeaderField("X-OAuth-Scopes")).thenReturn("user:email,repo");
when(httpURLConnectionMock.getResponseCode()).thenReturn(200);
String guser = "{\n \"login\": \"joe\",\n \"id\": 1, \"email\": \"[email protected]\", \"created_at\": \"2008-01-14T04:33:35Z\"}";
mockStatic(Stapler.class);
StaplerRequest request = mock(StaplerRequest.class);
when(Stapler.getCurrentRequest()).thenReturn(request);
when(HttpRequest.getInputStream(httpURLConnectionMock)).thenReturn(new ByteArrayInputStream(guser.getBytes("UTF-8")));
githubScm.validateAndCreate(req);
String id = githubScm.getCredentialId();
Assert.assertEquals(githubScm.getId(), id);
Assert.assertEquals("constructed url", "https://api.github.com/user", urlStringCaptor.getValue());
Assert.assertEquals("access token passed to github", accessToken.trim(), tokenCaptor.getValue());
}
protected User login(String userId, String fullName, String email) throws IOException {
j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
hudson.model.User bob = User.get(userId);
bob.setFullName(fullName);
if(email != null ) {
bob.addProperty(new Mailer.UserProperty(email));
}
UserDetails d = Jenkins.getInstance().getSecurityRealm().loadUserByUsername(bob.getId());
SecurityContextHolder.getContext().setAuthentication(new PrincipalAcegiUserToken(bob.getId(),bob.getId(),bob.getId(), d.getAuthorities(), bob.getId()));
return bob;
}