com.cloudbees.hudson.plugins.folder.Folder Java Examples

The following examples show how to use com.cloudbees.hudson.plugins.folder.Folder. 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: DockerAgentTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Issue("JENKINS-57162")
@Test
public void additionalDockerBuildArgsImageHash() throws Exception {
    DockerTestUtil.assumeDocker();

    sampleRepo.write("Dockerfile",  "FROM ubuntu:14.04\n\nARG someArg=thisArgHere\n\nRUN echo \"hi there, $someArg\" > /hi-there\n\n");
    sampleRepo.git("init");
    sampleRepo.git("add", "Dockerfile");
    sampleRepo.git("commit", "--message=Dockerfile");

    Folder folder = j.jenkins.createProject(Folder.class, "testFolder");
    expect("agent/additionalDockerBuildArgsParallel")
            .inFolder(folder)
            .withProjectName("parallelImageHashTest")
            .logContains("[Pipeline] { (foo)",
                    "-v /tmp:/tmp",
                    "docker build -t 8343c0815beb7a50c3676f09d7175d903a57f11b --build-arg someArg=thisOtherArg",
                    "The answer is 42",
                    "hi there, thisOtherArg",
                    "[Pipeline] { (bar)",
                    "docker build -t 4f8d74de557925eb9aacdfdf671b5e9de11b6086 --build-arg someArg=thisDifferentArg",
                    "The answer is 43",
                    "hi there, thisDifferentArg")
            .logNotContains("hi there, thisArgHere")
            .go();
}
 
Example #2
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test
public void grandParentOverride() throws Exception {
    Folder grandParent = j.createProject(Folder.class);
    getFolderStore(grandParent).addCredentials(Domain.global(), grandParentCred);
    grandParent.addProperty(new FolderConfig("parent_docker", "https://parent.registry", grandParentCred.getId()));
    Folder parent = grandParent.createProject(Folder.class, "testParent"); //Can be static since grandParent should be unique
    getFolderStore(parent).addCredentials(Domain.global(), folderCred);
    parent.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));

    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
            .inFolder(parent)
            .runFromRepo(false)
            .logContains("Docker Label is: folder_docker",
                    "Registry URL is: https://folder.registry",
                    "Registry Creds ID is: " + folderCred.getId())
            .logNotContains("Docker Label is: parent_docker",
                    "Registry URL is: https://parent.registry",
                    "Registry Creds ID is: " + grandParentCred.getId()).go();
}
 
Example #3
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Test
public void directParentNotSystem() throws Exception {
    GlobalConfig.get().setDockerLabel("config_docker");
    GlobalConfig.get().setRegistry(new DockerRegistryEndpoint("https://docker.registry", globalCred.getId()));
    Folder folder = j.createProject(Folder.class);
    getFolderStore(folder).addCredentials(Domain.global(), folderCred);
    folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
            .inFolder(folder)
            .runFromRepo(false)
            .logContains("Docker Label is: folder_docker",
                    "Registry URL is: https://folder.registry",
                    "Registry Creds ID is: " + folderCred.getId())
            .logNotContains("Docker Label is: config_docker",
                    "Registry URL is: https://docker.registry",
                    "Registry Creds ID is: " + globalCred.getId()).go();
}
 
Example #4
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 #5
Source File: GlobalConfigTest.java    From docker-workflow-plugin with MIT License 6 votes vote down vote up
@Issue("https://github.com/jenkinsci/docker-workflow-plugin/pull/202#issuecomment-597156438")
@LocalData
@Test
public void oldPackages() {
    story.then(r -> {
        assertEquals("GlobalConfig is translated", "docker", GlobalConfig.get().getDockerLabel());
        assertEquals("https://myreg/", GlobalConfig.get().getRegistry().getUrl());
        assertEquals("myreg", GlobalConfig.get().getRegistry().getCredentialsId());
        Folder d = r.jenkins.getItemByFullName("d", Folder.class);
        assertNotNull(d);
        FolderConfig c = d.getProperties().get(FolderConfig.class);
        assertNotNull("FolderConfig is translated", c);
        assertEquals("dokker", c.getDockerLabel());
        assertEquals("https://yourreg/", c.getRegistry().getUrl());
        assertEquals("yourreg", c.getRegistry().getCredentialsId());
        assertEquals("there is no old data", Collections.emptySet(), ExtensionList.lookupSingleton(OldDataMonitor.class).getData().keySet());
    });
}
 
Example #6
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testListCredentials() throws Exception {
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	StandardUsernamePasswordCredentials folderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			"folder-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	StandardUsernamePasswordCredentials globalCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
			"global-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");

	folderStore.addCredentials(Domain.global(), folderCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(globalCredentials);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	final WithAWSStep.DescriptorImpl descriptor = jenkinsRule.jenkins.getDescriptorByType(WithAWSStep.DescriptorImpl.class);

	// 3 options: Root credentials, folder credentials and "none"
	ListBoxModel list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());

	StandardUsernamePasswordCredentials systemCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
			"system-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	SystemCredentialsProvider.getInstance().getCredentials().add(systemCredentials);

	// Still 3 options: Root credentials, folder credentials and "none"
	list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());
}
 
Example #7
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
private CredentialsStore getFolderStore(Folder f) {
    Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
    CredentialsStore folderStore = null;
    for (CredentialsStore s : stores) {
        if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
            folderStore = s;
            break;
        }
    }
    return folderStore;
}
 
Example #8
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void withDefaults() throws Exception {
    Folder folder = j.createProject(Folder.class);
    getFolderStore(folder).addCredentials(Domain.global(), folderCred);
    getFolderStore(folder).addCredentials(Domain.global(), grandParentCred);
    folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfigWithOverride")
            .inFolder(folder)
            .runFromRepo(false)
            .logContains("Docker Label is: other-label",
                    "Registry URL is: https://other.registry",
                    "Registry Creds ID is: " + grandParentCred.getId()).go();
}
 
Example #9
Source File: DeclarativeDockerUtilsTest.java    From docker-workflow-plugin with MIT License 5 votes vote down vote up
@Test
public void directParent() throws Exception {
    Folder folder = j.createProject(Folder.class);
    getFolderStore(folder).addCredentials(Domain.global(), folderCred);
    folder.addProperty(new FolderConfig("folder_docker", "https://folder.registry", folderCred.getId()));
    expect("org/jenkinsci/plugins/docker/workflow/declarative/declarativeDockerConfig")
            .inFolder(folder)
            .runFromRepo(false)
            .logContains("Docker Label is: folder_docker",
                    "Registry URL is: https://folder.registry",
                    "Registry Creds ID is: " + folderCred.getId()).go();
}
 
Example #10
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
private CredentialsStore getFolderStore(Folder f) {
    Iterable<CredentialsStore> stores = CredentialsProvider.lookupStores(f);
    CredentialsStore folderStore = null;
    for (CredentialsStore s : stores) {
        if (s.getProvider() instanceof FolderCredentialsProvider && s.getContext() == f) {
            folderStore = s;
            break;
        }
    }
    return folderStore;
}
 
Example #11
Source File: GitHubNotificationPipelineStepTest.java    From pipeline-githubnotify-step-plugin with MIT License 5 votes vote down vote up
@Test
public void buildWithFolderCredentials() throws Exception {

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

    Folder f = jenkins.jenkins.createProject(Folder.class, "folder" + jenkins.jenkins.getItems().size());
    CredentialsStore folderStore = getFolderStore(f);
    folderStore.addCredentials(Domain.global(),
            new DummyCredentials(CredentialsScope.GLOBAL, "user", "password"));

    WorkflowJob p = f.createProject(WorkflowJob.class, "p");
    p.setDefinition(new CpsFlowDefinition(
            "githubNotify account: 'raul-arabaolaza', context: 'ATH Results', " +
                    "credentialsId: 'dummy', description: 'All tests are OK', " +
                    "repo: 'acceptance-test-harness', sha: '0b5936eb903d439ac0c0bf84940d73128d5e9487', " +
                    "status: 'SUCCESS', targetUrl: 'http://www.cloudbees.com'"
    ));
    WorkflowRun b1 = p.scheduleBuild2(0).waitForStart();
    jenkins.assertBuildStatus(Result.SUCCESS, jenkins.waitForCompletion(b1));
}
 
Example #12
Source File: CodeBuildStep.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems() {
    final ListBoxModel selections = new ListBoxModel();

    SystemCredentialsProvider s = SystemCredentialsProvider.getInstance();
    Set<String> displayCredentials = new HashSet<>();

    for (Credentials c: s.getCredentials()) {
        if (c instanceof CodeBuildBaseCredentials) {
            displayCredentials.add(((CodeBuildBaseCredentials) c).getId());
        }
    }

    Jenkins instance = Jenkins.getInstance();
    if(instance != null) {
        List<Folder> folders = instance.getAllItems(Folder.class);
        for(Folder folder: folders) {
            List<Credentials> creds = CredentialsProvider.lookupCredentials(Credentials.class, (Item) folder);
            for(Credentials cred: creds) {
                if (cred instanceof CodeBuildBaseCredentials) {
                    displayCredentials.add(((CodeBuildBaseCredentials) cred).getId());
                }
            }
        }
    }


    for(String credString: displayCredentials) {
        selections.add(credString);
    }

    return selections;
}
 
Example #13
Source File: CodeBuilder.java    From aws-codebuild-jenkins-plugin with Apache License 2.0 5 votes vote down vote up
public ListBoxModel doFillCredentialsIdItems() {
    final ListBoxModel selections = new ListBoxModel();

    SystemCredentialsProvider s = SystemCredentialsProvider.getInstance();
    Set<String> displayCredentials = new HashSet<>();

    for (Credentials c: s.getCredentials()) {
        if (c instanceof CodeBuildBaseCredentials) {
            displayCredentials.add(((CodeBuildBaseCredentials) c).getId());
        }
    }

    Jenkins instance = Jenkins.getInstance();
    if(instance != null) {
        List<Folder> folders = instance.getAllItems(Folder.class);
        for(Folder folder: folders) {
            List<Credentials> creds = CredentialsProvider.lookupCredentials(Credentials.class, (Item) folder);
            for(Credentials cred: creds) {
                if (cred instanceof CodeBuildBaseCredentials) {
                    displayCredentials.add(((CodeBuildBaseCredentials) cred).getId());
                }
            }
        }
    }


    for(String credString: displayCredentials) {
        selections.add(credString);
    }

    return selections;
}
 
Example #14
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testListAWSCredentials() throws Exception {

	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			"test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	AmazonWebServicesCredentials globalAmazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			"global-test-aws-creds", "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");

	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().getCredentials().add(globalAmazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	final WithAWSStep.DescriptorImpl descriptor = jenkinsRule.jenkins.getDescriptorByType(WithAWSStep.DescriptorImpl.class);

	// 3 options: Root credentials, folder credentials and "none"
	ListBoxModel list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());

	StandardUsernamePasswordCredentials systemCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.SYSTEM,
			"system-creds", "test-creds", "aws-access-key-id", "aws-secret-access-key");
	SystemCredentialsProvider.getInstance().getCredentials().add(systemCredentials);

	// Still 3 options: Root credentials, folder credentials and "none"
	list = descriptor.doFillCredentialsItems(job);
	Assert.assertEquals(3, list.size());
}
 
Example #15
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithAWSIamMFAFolderCredentials() throws Exception {

	String folderCredentialsId = "folders-aws-creds";

	// Create a folder with credentials in its store
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			folderCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(folderCredentialsId);

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithAWSIamMFAFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + folderCredentialsId + "', iamMfaToken: '1234567') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	WorkflowRun workflowRun = job.scheduleBuild2(0).get();
	jenkinsRule.waitForCompletion(workflowRun);
	jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun);
	jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun);
	jenkinsRule.assertLogContains("Constructing AWS Credentials", workflowRun);
	jenkinsRule.assertLogContains("utilizing MFA Token", workflowRun);

}
 
Example #16
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithAWSFolderCredentials() throws Exception {

	String folderCredentialsId = "folders-aws-creds";

	// Create a folder with credentials in its store
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	AmazonWebServicesCredentials amazonWebServicesCredentials = new AWSCredentialsImpl(CredentialsScope.GLOBAL,
			folderCredentialsId, "global-aws-access-key-id", "global-aws-secret-access-key", "Aws-Description",
			"Arn::Something:or:Other", "12345678");
	folderStore.addCredentials(Domain.global(), amazonWebServicesCredentials);
	SystemCredentialsProvider.getInstance().save();

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(folderCredentialsId);

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithAWSFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
			+ "node {\n"
			+ "  withAWS (credentials: '" + folderCredentialsId + "') {\n"
			+ "    echo 'It works!'\n"
			+ "  }\n"
			+ "}\n", true)
	);
	WorkflowRun workflowRun = job.scheduleBuild2(0).get();
	jenkinsRule.waitForCompletion(workflowRun);
	jenkinsRule.assertBuildStatus(Result.FAILURE, workflowRun);
	jenkinsRule.assertLogContains("The security token included in the request is invalid.", workflowRun);
	jenkinsRule.assertLogContains("Constructing AWS Credentials", workflowRun);

}
 
Example #17
Source File: WithAWSStepTest.java    From pipeline-aws-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void testStepWithFolderCredentials() throws Exception {

	String folderCredentialsId = "folders-aws-creds";

	// Create a folder with credentials in its store
	Folder folder = jenkinsRule.jenkins.createProject(Folder.class, "folder" + jenkinsRule.jenkins.getItems().size());
	CredentialsStore folderStore = this.getFolderStore(folder);
	StandardUsernamePasswordCredentials inFolderCredentials = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL,
																								  folderCredentialsId, "test-folder-creds", "folder-aws-access-key-id", "folder-aws-secret-access-key");
	folderStore.addCredentials(Domain.global(), inFolderCredentials);
	SystemCredentialsProvider.getInstance().save();

	List<String> credentialIds = new ArrayList<>();
	credentialIds.add(folderCredentialsId);

	WorkflowJob job = folder.createProject(WorkflowJob.class, "testStepWithFolderCredentials");
	job.setDefinition(new CpsFlowDefinition(""
													+ "node {\n"
													+ "  withAWS (credentials: '" + folderCredentialsId + "') {\n"
													+ "    echo 'It works!'\n"
													+ "  }\n"
													+ "}\n", true)
	);
	jenkinsRule.assertBuildStatusSuccess(job.scheduleBuild2(0));

}
 
Example #18
Source File: GogsWebHookPluginsTest.java    From gogs-webhook-plugin with MIT License 5 votes vote down vote up
@Test
public void testCloudBeesFolder() throws Exception {
    Folder folder = createFolder(FOLDERNAME);

    FreeStyleProject project = folder.createProject(FreeStyleProject.class, PROJECTNAME);

    Job job = GogsUtils.find(FOLDERNAME + "/" + PROJECTNAME, Job.class);
    assertEquals("Couldn't find " + FOLDERNAME + "/" + PROJECTNAME, job, project);
}
 
Example #19
Source File: GerritWebHookTriggerTest.java    From gerrit-code-review-plugin with Apache License 2.0 5 votes vote down vote up
@Test
public void gerritWebHookShouldTriggerMultiBranchPipelineProjectWithFolder() throws Exception {
  Folder f = j.jenkins.createProject(Folder.class, "folder");
  WorkflowMultiBranchProject mp = f.createProject(WorkflowMultiBranchProject.class, projectName);
  mp.getSourcesList().add(new BranchSource(getGerritSCMSource()));

  assertEquals(httpStatusOfPostGerritEventBodyToWebhookURI(), HttpServletResponse.SC_OK);
  j.waitUntilNoActivity();

  assertEquals(Result.SUCCESS, mp.getIndexing().getResult());
}
 
Example #20
Source File: RestartSurvivabilityTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
private void checkConfiguration() {
    Jenkins jenkins = Jenkins.get();
    try (ACLContext ignored = ACL.as(User.getById("admin", true))) {
        assertTrue(jenkins.hasPermission(Jenkins.ADMINISTER));
    }

    try (ACLContext ignored = ACL.as(User.getById("user1", true))) {
        Folder folder = (Folder) jenkins.getItem("folder");
        assertNotNull(folder);
        assertTrue(jenkins.hasPermission(Jenkins.READ));
        assertTrue(folder.hasPermission(Item.READ));
        assertFalse(folder.hasPermission(Item.CONFIGURE));
        assertFalse(jenkins.hasPermission(Jenkins.ADMINISTER));

        Computer computer = jenkins.getComputer("foo");
        assertNotNull(computer);
        assertTrue(computer.hasPermission(Computer.CONFIGURE));
        assertFalse(computer.hasPermission(Computer.DELETE));
    }

    AuthorizationStrategy a = Jenkins.get().getAuthorizationStrategy();
    assertTrue(a instanceof FolderBasedAuthorizationStrategy);
    FolderBasedAuthorizationStrategy strategy = (FolderBasedAuthorizationStrategy) a;
    assertEquals(strategy.getGlobalRoles().size(), 2);
    assertEquals(strategy.getFolderRoles().size(), 1);
    assertEquals(strategy.getAgentRoles().size(), 1);
}
 
Example #21
Source File: RestartSurvivabilityTest.java    From folder-auth-plugin with MIT License 5 votes vote down vote up
@Test
@Issue("JENKINS-58485")
public void shouldHaveSameConfigurationAfterRestart() {
    rule.addStep(new Statement() {
        @Override
        public void evaluate() throws Exception {
            rule.j.createProject(Folder.class, "folder");
            rule.j.jenkins.setSecurityRealm(rule.j.createDummySecurityRealm());
            rule.j.jenkins.setAuthorizationStrategy(createNewFolderBasedAuthorizationStrategy());
            rule.j.jenkins.addNode(rule.j.createSlave("foo", null, null));
            checkConfiguration();
        }
    });

    rule.addStep(new Statement() {
        @Override
        public void evaluate() {
            rule.j.jenkins.setSecurityRealm(rule.j.createDummySecurityRealm());
            checkConfiguration();

            // JENKINS-58485
            XStream2 xStream = new XStream2();
            String xml = xStream.toXML(rule.j.jenkins.getAuthorizationStrategy());
            assertFalse(xml.contains("ConcurrentHashMap$KeySetView"));
        }
    });
}
 
Example #22
Source File: ConfigurationAsCodeTest.java    From folder-auth-plugin with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    j.jenkins.addNode(new DumbSlave("agent1", "", new JNLPLauncher(true)));
    folder = j.jenkins.createProject(Folder.class, "root");
}
 
Example #23
Source File: GogsWebHookPluginsTest.java    From gogs-webhook-plugin with MIT License 4 votes vote down vote up
private Folder createFolder(String folder) throws IOException {
    return r.jenkins.createProject(Folder.class, folder);
}
 
Example #24
Source File: FolderIT.java    From hashicorp-vault-plugin with MIT License 4 votes vote down vote up
@Before
public void setupJenkins() throws IOException {
    GlobalVaultConfiguration globalConfig = GlobalConfiguration.all()
        .get(GlobalVaultConfiguration.class);

    VaultConfiguration vaultConfig = new VaultConfiguration();
    vaultConfig.setVaultUrl("http://global-vault-url.com");
    vaultConfig.setVaultCredentialId(GLOBAL_CREDENTIALS_ID_1);
    vaultConfig.setFailIfNotFound(false);
    vaultConfig.setVaultNamespace("mynamespace");
    vaultConfig.setTimeout(TIMEOUT);

    globalConfig.setConfiguration(vaultConfig);
    globalConfig.save();

    FOLDER_1_CREDENTIAL = createTokenCredential(FOLDER_1_CREDENTIALS_ID);
    FOLDER_2_CREDENTIAL = createTokenCredential(FOLDER_2_CREDENTIALS_ID);

    FolderCredentialsProvider.FolderCredentialsProperty folder1CredProperty = new FolderCredentialsProvider.FolderCredentialsProperty(
        new DomainCredentials[]{
            new DomainCredentials(Domain.global(),
                Collections.singletonList(FOLDER_1_CREDENTIAL))});

    FolderCredentialsProvider.FolderCredentialsProperty folder2CredProperty = new FolderCredentialsProvider.FolderCredentialsProperty(
        new DomainCredentials[]{
            new DomainCredentials(Domain.global(),
                Collections.singletonList(FOLDER_2_CREDENTIAL))});

    GLOBAL_CREDENTIAL_1 = createTokenCredential(GLOBAL_CREDENTIALS_ID_1);
    GLOBAL_CREDENTIAL_2 = createTokenCredential(GLOBAL_CREDENTIALS_ID_2);

    SystemCredentialsProvider.getInstance()
        .setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Arrays
            .asList(GLOBAL_CREDENTIAL_1, GLOBAL_CREDENTIAL_2)));

    this.folder1 = jenkins.createProject(Folder.class, "folder1");
    this.folder2 = jenkins.createProject(Folder.class, "folder2");

    folder1.addProperty(folder1CredProperty);
    folder2.addProperty(folder2CredProperty);

    projectInFolder1 = this.folder1.createProject(FreeStyleProject.class, "projectInFolder1");
    projectInFolder2 = this.folder2.createProject(FreeStyleProject.class, "projectInFolder2");
}
 
Example #25
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
@Test
public void maven_global_settings_defined_through_folder_config_and_config_file_provider() throws Exception {

    String mavenGlobalSettings = "<?xml version='1.0' encoding='UTF-8'?>\n" +
            "<settings \n" +
            "        xmlns='http://maven.apache.org/SETTINGS/1.0.0'\n" +
            "        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n" +
            "        xsi:schemaLocation='http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd'>\n" +
            "    <servers>\n" +
            "       <server>\n" +
            "           <id>id-global-settings-test-from-config-file-provider-on-a-folder</id>\n" +
            "       </server>\n" +
            "    </servers>\n" +
            "</settings>\n";

    GlobalMavenSettingsConfig mavenGlobalSettingsConfig = new GlobalMavenSettingsConfig("maven-global-config-test-folder", "maven-global-config-test-folder", "",
        mavenGlobalSettings);

    String pipelineScript = "node () {\n" +
            "    writeFile file: 'pom.xml', text: '''<?xml version='1.0' encoding='UTF-8'?>\n" +
            "<project\n" +
            "        xmlns='http://maven.apache.org/POM/4.0.0' \n" +
            "        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \n" +
            "        xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd'>\n" +
            "    <modelVersion>4.0.0</modelVersion>\n" +
            "    <groupId>com.example</groupId>\n" +
            "    <artifactId>my-artifact</artifactId>\n" +
            "    <version>1.0.0-SNAPSHOT</version>\n" +
            "    <packaging>pom</packaging>\n" +
            "</project>'''\n" +
            "\n" +
            "    withMaven(maven: 'apache-maven-3.5.0') {\n" +
            "        sh 'mvn help:effective-settings'\n" +
            "    }\n" +
            "}\n";

    GlobalConfigFiles.get().save(mavenGlobalSettingsConfig);

    Folder folder = jenkinsRule.createProject(Folder.class, "folder");
    MavenConfigFolderOverrideProperty configOverrideProperty = new MavenConfigFolderOverrideProperty();
    configOverrideProperty.setOverride(true);
    configOverrideProperty.setGlobalSettings(new MvnGlobalSettingsProvider(mavenGlobalSettingsConfig.id));
    folder.addProperty(configOverrideProperty);

    try {
        WorkflowJob pipeline = folder.createProject(WorkflowJob.class,
            "build-on-master-with-maven-global-settings-defined-in-jenkins-global-config-with-config-file-provider");
        pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
        WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));
        jenkinsRule.assertLogContains(
            "[withMaven] using overriden Maven global settings by folder 'folder'. Config File Provider maven global settings file 'maven-global-config-test-folder'",
            build);
        jenkinsRule.assertLogContains("<id>id-global-settings-test-from-config-file-provider-on-a-folder</id>", build);
    } finally {
        GlobalMavenConfig.get().setGlobalSettingsProvider(null);
        GlobalConfigFiles.get().remove(mavenGlobalSettingsConfig.id);
    }
}
 
Example #26
Source File: WithMavenStepOnMasterTest.java    From pipeline-maven-plugin with MIT License 4 votes vote down vote up
@Test
public void maven_settings_defined_through_folder_config_and_config_file_provider() throws Exception {

    String mavenSettings = "<?xml version='1.0' encoding='UTF-8'?>\n" +
            "<settings \n" +
            "        xmlns='http://maven.apache.org/SETTINGS/1.0.0'\n" +
            "        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'\n" +
            "        xsi:schemaLocation='http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd'>\n" +
            "    <servers>\n" +
            "       <server>\n" +
            "           <id>id-settings-test-through-config-file-provider-on-a-folder</id>\n" +
            "       </server>\n" +
            "    </servers>\n" +
            "</settings>\n";
    MavenSettingsConfig mavenSettingsConfig = new MavenSettingsConfig("maven-config-test-folder", "maven-config-test-folder", "", mavenSettings, false, null);

    String pipelineScript = "node () {\n" +
            "    writeFile file: 'pom.xml', text: '''<?xml version='1.0' encoding='UTF-8'?>\n" +
            "<project\n" +
            "        xmlns='http://maven.apache.org/POM/4.0.0' \n" +
            "        xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' \n" +
            "        xsi:schemaLocation='http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd'>\n" +
            "    <modelVersion>4.0.0</modelVersion>\n" +
            "    <groupId>com.example</groupId>\n" +
            "    <artifactId>my-artifact</artifactId>\n" +
            "    <version>1.0.0-SNAPSHOT</version>\n" +
            "    <packaging>pom</packaging>\n" +
            "</project>'''\n" +
            "\n" +
            "    withMaven(maven: 'apache-maven-3.5.0') {\n" +
            "        sh 'mvn help:effective-settings'\n" +
            "    }\n" +
            "}\n";
    GlobalConfigFiles.get().save(mavenSettingsConfig);

    Folder folder = jenkinsRule.createProject(Folder.class, "folder");
    MavenConfigFolderOverrideProperty configOverrideProperty = new MavenConfigFolderOverrideProperty();
    configOverrideProperty.setOverride(true);
    GlobalMavenConfig globalMavenConfig = GlobalMavenConfig.get();
    configOverrideProperty.setGlobalSettings(globalMavenConfig.getGlobalSettingsProvider());
    configOverrideProperty.setSettings(new MvnSettingsProvider(mavenSettingsConfig.id));
    folder.addProperty(configOverrideProperty);

    try {
        WorkflowJob pipeline = folder.createProject(WorkflowJob.class, "build-on-master-with-maven-settings-defined-in-jenkins-global-config-with-config-file-provider");
        pipeline.setDefinition(new CpsFlowDefinition(pipelineScript, true));
        WorkflowRun build = jenkinsRule.assertBuildStatus(Result.SUCCESS, pipeline.scheduleBuild2(0));
        jenkinsRule.assertLogContains("[withMaven] using overriden Maven settings by folder 'folder'. Config File Provider maven settings file 'maven-config-test-folder'",
            build);
        jenkinsRule.assertLogContains("<id>id-settings-test-through-config-file-provider-on-a-folder</id>", build);
    } finally {
        configOverrideProperty.setOverride(false);
    }
}
 
Example #27
Source File: GithubOrgFolderPermissionsTest.java    From blueocean-plugin with MIT License 4 votes vote down vote up
public TestOrganizationFactoryImpl() throws IOException {
    Folder f = Jenkins.getInstance().createProject(Folder.class, "CustomOrg");
    instance = new OrganizationImpl("custom", f);
}
 
Example #28
Source File: RoleStrategyTest.java    From configuration-as-code-plugin with MIT License 4 votes vote down vote up
@Test
@Issue("Issue #48")
@ConfiguredWithCode("RoleStrategy1.yml")
public void shouldReadRolesCorrectly() throws Exception {
    j.jenkins.setSecurityRealm(j.createDummySecurityRealm());
    User admin = User.getById("admin", false);
    User user1 = User.getById("user1", false);
    User user2 = User.getById("user2", true);
    Computer agent1 = j.jenkins.getComputer("agent1");
    Computer agent2 = j.jenkins.getComputer("agent2");
    Folder folderA = j.jenkins.createProject(Folder.class, "A");
    FreeStyleProject jobA1 = folderA.createProject(FreeStyleProject.class, "1");
    Folder folderB = j.jenkins.createProject(Folder.class, "B");
    folderB.createProject(FreeStyleProject.class, "2");

    AuthorizationStrategy s = j.jenkins.getAuthorizationStrategy();
    assertThat("Authorization Strategy has been read incorrectly",
            s, instanceOf(RoleBasedAuthorizationStrategy.class));
    RoleBasedAuthorizationStrategy rbas = (RoleBasedAuthorizationStrategy) s;

    Map<Role, Set<String>> globalRoles = rbas.getGrantedRoles(RoleBasedAuthorizationStrategy.GLOBAL);
    assertThat(globalRoles.size(), equalTo(2));

    // Admin has configuration access
    assertHasPermission(admin, j.jenkins, Jenkins.ADMINISTER, Jenkins.READ);
    assertHasPermission(user1, j.jenkins, Jenkins.READ);
    assertHasNoPermission(user1, j.jenkins, Jenkins.ADMINISTER);

    // Folder A is restricted to admin
    assertHasPermission(admin, folderA, Item.CONFIGURE);
    assertHasPermission(user1, folderA, Item.READ, Item.DISCOVER);
    assertHasNoPermission(user1, folderA, Item.CONFIGURE, Item.DELETE, Item.BUILD);

    // But they have access to jobs in Folder A
    assertHasPermission(admin, folderA, Item.CONFIGURE, Item.CANCEL);
    assertHasPermission(user1, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE);
    assertHasPermission(user2, jobA1, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD, Item.DELETE);
    assertHasNoPermission(user1, folderA, Item.CANCEL);

    // FolderB is editable by user2, but he cannot delete it
    assertHasPermission(user2, folderB, Item.READ, Item.DISCOVER, Item.CONFIGURE, Item.BUILD);
    assertHasNoPermission(user2, folderB, Item.DELETE);
    assertHasNoPermission(user1, folderB, Item.CONFIGURE, Item.BUILD, Item.DELETE);

    // Only user1 can run on agent1, but he still cannot configure it
    assertHasPermission(admin, agent1, Computer.CONFIGURE, Computer.DELETE, Computer.BUILD);
    assertHasPermission(user1, agent1, Computer.BUILD);
    assertHasNoPermission(user1, agent1, Computer.CONFIGURE, Computer.DISCONNECT);

    // Same user still cannot build on agent2
    assertHasNoPermission(user1, agent2, Computer.BUILD);
}
 
Example #29
Source File: FolderBasedAuthorizationStrategyTest.java    From folder-auth-plugin with MIT License 4 votes vote down vote up
@Before
public void setUp() throws Exception {
    Jenkins jenkins = jenkinsRule.jenkins;
    jenkins.setSecurityRealm(jenkinsRule.createDummySecurityRealm());

    FolderBasedAuthorizationStrategy strategy = new FolderBasedAuthorizationStrategy(Collections.emptySet(),
            Collections.emptySet(), Collections.emptySet());
    jenkins.setAuthorizationStrategy(strategy);

    final String adminRoleName = "adminRole";
    final String overallReadRoleName = "overallRead";

    FolderAuthorizationStrategyAPI.addGlobalRole(new GlobalRole(adminRoleName,
            wrapPermissions(FolderAuthorizationStrategyManagementLink.getSafePermissions(
                    new HashSet<>(PermissionGroup.getAll())))));

    FolderAuthorizationStrategyAPI.assignSidToGlobalRole("admin", adminRoleName);

    FolderAuthorizationStrategyAPI.addGlobalRole(new GlobalRole(overallReadRoleName, wrapPermissions(Permission.READ)));
    FolderAuthorizationStrategyAPI.assignSidToGlobalRole("authenticated", overallReadRoleName);

    FolderAuthorizationStrategyAPI.addFolderRole(new FolderRole("folderRole1", wrapPermissions(Item.READ),
            ImmutableSet.of("root")));
    FolderAuthorizationStrategyAPI.assignSidToFolderRole("user1", "folderRole1");
    FolderAuthorizationStrategyAPI.assignSidToFolderRole("user2", "folderRole1");

    FolderAuthorizationStrategyAPI.addFolderRole(new FolderRole("folderRole2", wrapPermissions(Item.CONFIGURE, Item.DELETE),
            ImmutableSet.of("root/child1")));
    FolderAuthorizationStrategyAPI.assignSidToFolderRole("user2", "folderRole2");

    /*
     * Folder hierarchy for the test
     *
     *             root
     *             /  \
     *        child1   child2
     *          /        \
     *        child3     job1
     *         /
     *        job2
     */

    root = jenkins.createProject(Folder.class, "root");
    child1 = root.createProject(Folder.class, "child1");
    child2 = root.createProject(Folder.class, "child2");
    child3 = child1.createProject(Folder.class, "child3");

    job1 = child2.createProject(FreeStyleProject.class, "job1");
    job2 = child3.createProject(FreeStyleProject.class, "job2");

    admin = User.getById("admin", true);
    user1 = User.getById("user1", true);
    user2 = User.getById("user2", true);
}
 
Example #30
Source File: FolderRoleBenchmark.java    From folder-auth-plugin with MIT License 4 votes vote down vote up
@Override
public void setup() throws Exception {
    Jenkins jenkins = getJenkins();
    jenkins.setSecurityRealm(new JenkinsRule().createDummySecurityRealm());

    Set<GlobalRole> globalRoles = ImmutableSet.of((
            new GlobalRole("ADMIN", wrapPermissions(Jenkins.ADMINISTER), Collections.singleton("admin"))),
        new GlobalRole("read", wrapPermissions(Jenkins.READ), Collections.singleton("authenticated"))
    );

    Set<FolderRole> folderRoles = new HashSet<>();

    Random random = new Random(100L);

    // create the folders
    for (int i = 0; i < 10; i++) {
        String topFolderName = "TopFolder" + i;
        Folder folder = jenkins.createProject(Folder.class, topFolderName);

        Set<String> users = new HashSet<>();
        for (int k = 0; k < random.nextInt(5); k++) {
            users.add("user" + random.nextInt(100));
        }

        FolderRole userRole = new FolderRole(topFolderName, wrapPermissions(Item.READ, Item.DISCOVER),
            Collections.singleton(topFolderName), users);

        folderRoles.add(userRole);

        for (int j = 0; j < 5; j++) {
            Folder bottom = folder.createProject(Folder.class, "BottomFolder" + j);

            Set<String> maintainers = new HashSet<>(2);
            maintainers.add("user" + random.nextInt(100));
            maintainers.add("user" + random.nextInt(100));

            FolderRole maintainerRole = new FolderRole(bottom.getFullName(),
                wrapPermissions(Item.READ, Item.DISCOVER, Item.CREATE),
                Collections.singleton(topFolderName), maintainers);

            Set<String> admin = Collections.singleton("user" + random.nextInt(100));

            FolderRole folderAdminRole = new FolderRole(bottom.getFullName(), wrapPermissions(Item.READ, Item.DISCOVER,
                Item.CONFIGURE, Item.CREATE), Collections.singleton(topFolderName), admin);
            folderRoles.add(maintainerRole);
            folderRoles.add(folderAdminRole);

            for (int k = 0; k < 5; k++) {
                bottom.createProject(FreeStyleProject.class, "Project" + k);
            }
        }
    }

    jenkins.setAuthorizationStrategy(new FolderBasedAuthorizationStrategy(globalRoles, folderRoles,
        Collections.emptySet()));
}