jenkins.setAuthorizationStrategy(authStrategy);
j.setDisableRememberMe(security.optBoolean("disableRememberMe", false)); j.setSecurityRealm(SecurityRealm.all().newInstanceFromRadioList(security, "realm")); j.setAuthorizationStrategy(AuthorizationStrategy.all().newInstanceFromRadioList(security, "authorization")); } else { j.disableSecurity();
private void restoreAuth() { if (originalSecurityRealm != null) { rule.jenkins.setSecurityRealm(originalSecurityRealm); originalSecurityRealm = null; } if (originalAuthorizationStrategy != null) { rule.jenkins.setAuthorizationStrategy(originalAuthorizationStrategy); originalAuthorizationStrategy = null; } if (originalSecurityContext != null) { SecurityContextHolder.setContext(originalSecurityContext); originalSecurityContext = null; } }
/** * Called on role management form's submission. */ @RequirePOST @Restricted(NoExternalUse.class) public void doRolesSubmit(StaplerRequest req, StaplerResponse rsp) throws UnsupportedEncodingException, ServletException, FormException, IOException { checkAdminPerm(); req.setCharacterEncoding("UTF-8"); JSONObject json = req.getSubmittedForm(); AuthorizationStrategy strategy = this.newInstance(req, json); instance().setAuthorizationStrategy(strategy); // Persist the data persistChanges(); }
private void setAuth() { if (permissions.isEmpty()) return; JenkinsRule.DummySecurityRealm realm = rule.createDummySecurityRealm(); realm.addGroups(username, "group"); originalSecurityRealm = rule.jenkins.getSecurityRealm(); rule.jenkins.setSecurityRealm(realm); originalAuthorizationStrategy = rule.jenkins.getAuthorizationStrategy(); rule.jenkins.setAuthorizationStrategy(new GrantPermissions(username, permissions)); command.setTransportAuth(user().impersonate()); // Otherwise it is SYSTEM, which would be relevant for a command overriding main: originalSecurityContext = ACL.impersonate(Jenkins.ANONYMOUS); }
@Test public void doFillCredentialsIdItemsWithoutJobWhenAdmin() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy(); as.add(Jenkins.ADMINISTER, "alice"); r.jenkins.setAuthorizationStrategy(as); final UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "test", "bob", "s3cr3t"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); ACL.impersonate(User.get("alice").impersonate(), new Runnable() { @Override public void run() { ListBoxModel options = r.jenkins.getDescriptorByType(MercurialSCM.DescriptorImpl.class).doFillCredentialsIdItems(null, "http://nowhere.net/"); assertEquals(CredentialsNameProvider.name(c), options.get(1).name); } }); }
/** * Lock down the instance. * @param j JenkinsRule. * @throws Exception throw if so. */ public static void lockDown(JenkinsRule j) throws Exception { SecurityRealm securityRealm = j.createDummySecurityRealm(); j.getInstance().setSecurityRealm(securityRealm); j.getInstance().setAuthorizationStrategy( new MockAuthorizationStrategy().grant(Jenkins.READ).everywhere().toAuthenticated()); }
r.jenkins.setAuthorizationStrategy(as); folder.addProperty(new com.cloudbees.hudson.plugins.folder.properties.AuthorizationMatrixProperty(grantedPermissions));
@Test public void invalidUser() throws Exception { File testPath = writeJenkinsfileToTmpFile("simplePipeline"); j.jenkins.setSecurityRealm(j.createDummySecurityRealm()); j.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy() .grant(Jenkins.ADMINISTER).everywhere().to("bob") .grant(Jenkins.READ, Item.READ, Item.EXTENDED_READ).everywhere().to("alice")); final CLICommandInvoker.Result result = command.withStdin(FileUtils.openInputStream(testPath)).invoke(); assertThat(result, not(succeeded())); assertThat(result.stderr(), containsString("ERROR: anonymous is missing the Overall/Read permission")); declarativeLinterCommand.setTransportAuth(User.get("alice").impersonate()); final CLICommandInvoker.Result result2 = command.withStdin(FileUtils.openInputStream(testPath)).invoke(); assertThat(result2, succeeded()); assertThat(result2, hasNoErrorOutput()); assertThat(result2.stdout(), containsString("Jenkinsfile successfully validated.")); }
@Issue("SECURITY-158") @Test public void doFillCredentialsIdItems() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy(); as.add(Jenkins.READ, "alice"); as.add(Jenkins.READ, "bob"); r.jenkins.setAuthorizationStrategy(as); FreeStyleProject p1 = r.createFreeStyleProject("p1"); FreeStyleProject p2 = r.createFreeStyleProject("p2"); p2.addProperty(new AuthorizationMatrixProperty(Collections.singletonMap(Item.CONFIGURE, Collections.singleton("bob")))); UsernamePasswordCredentialsImpl c = new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, null, "test", "bob", "s3cr3t"); CredentialsProvider.lookupStores(r.jenkins).iterator().next().addCredentials(Domain.global(), c); assertCredentials("alice", null); assertCredentials("alice", p1); assertCredentials("alice", p2); assertCredentials("bob", null); assertCredentials("bob", p1); assertCredentials("bob", p2, c); } private void assertCredentials(String user, final Job<?,?> owner, Credentials... expected) {
@Issue("SECURITY-303") @Test public void credentialsAccess() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.READ, Item.READ, Item.BUILD, Item.CONFIGURE).everywhere().to("devlead"). grant(Jenkins.READ, Item.READ, Item.BUILD).everywhere().to("user")); SystemCredentialsProvider.getInstance().setDomainCredentialsMap(Collections.singletonMap(Domain.global(), Collections.<Credentials>singletonList( new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "svncreds", null, "svn", "s3cr3t")))); r.createFreeStyleProject("p"); assertSniff("devlead", "svn:s3cr3t", /* server response is bad, Jenkins should say so */ false); assertSniff("user", null, /* Jenkins should not even try to connect, pretend it is OK */ true); } private void assertSniff(String user, String sniffed, boolean ok) throws Exception {
@Issue("SECURITY-1266") @Test public void configureRequired() throws Exception { CpsFlowDefinition.DescriptorImpl d = r.jenkins.getDescriptorByType(CpsFlowDefinition.DescriptorImpl.class); r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); // Set up an administrator, and three developer users with varying levels of access. r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.ADMINISTER).everywhere().to("admin"). grant(Jenkins.READ, Item.CONFIGURE).everywhere().to("dev1"). grant(Jenkins.READ).everywhere().to("dev2")); WorkflowJob job = r.jenkins.createProject(WorkflowJob.class, "w"); try (ACLContext context = ACL.as(User.getById("admin", true))) { assertThat(d.doCheckScriptCompile(job, "echo 'hello").toString(), containsString("fail")); } try (ACLContext context = ACL.as(User.getById("dev1", true))) { assertThat(d.doCheckScriptCompile(job, "echo 'hello").toString(), containsString("fail")); } try (ACLContext context = ACL.as(User.getById("dev2", true))) { assertThat(d.doCheckScriptCompile(job, "echo 'hello").toString(), containsString("success")); } } }
@Test public void getDestinations() throws Exception { Folder d1 = r.jenkins.createProject(Folder.class, "d1"); // where we start FreeStyleProject j = d1.createProject(FreeStyleProject.class, "j"); final Folder d2 = r.jenkins.createProject(Folder.class, "d2"); // where we could go Folder d3 = r.jenkins.createProject(Folder.class, "d3"); // where we cannot r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.READ, Item.READ).everywhere().to("joe"). grant(Item.CREATE).onItems(d2).to("joe")); try (ACLContext ctx = ACL.as(User.get("joe"))) { assertEquals(Arrays.asList(d1, d2), new StandardHandler().validDestinations(j)); assertEquals(Arrays.asList(r.jenkins, d2), new StandardHandler().validDestinations(d1)); assertNotEquals(Arrays.asList(r.jenkins, d3), new StandardHandler().validDestinations(j)); assertNotEquals(Arrays.asList(d1, d3), new StandardHandler().validDestinations(d1)); } }
@Issue("JENKINS-32487") @Test public void shouldAssignPropertyOwnerOnCreationAndReload() throws Exception { Folder folder = r.jenkins.createProject(Folder.class, "myFolder"); ProjectMatrixAuthorizationStrategy as = new ProjectMatrixAuthorizationStrategy(); // Need to do this to avoid JENKINS-9774 as.add(Jenkins.ADMINISTER, "alice"); r.jenkins.setAuthorizationStrategy(as); // We add a stub property to generate the persisted list // Then we ensure owner is being assigned properly. folder.addProperty(new FolderCredentialsProvider.FolderCredentialsProperty(new DomainCredentials[0])); assertPropertyOwner("After property add", folder, FolderCredentialsProvider.FolderCredentialsProperty.class); // Reload and ensure that the property owner is set r.jenkins.reload(); Folder reloadedFolder = r.jenkins.getItemByFullName("myFolder", Folder.class); assertPropertyOwner("After reload", reloadedFolder, FolderCredentialsProvider.FolderCredentialsProperty.class); }
strategy.grant(Computer.BUILD).everywhere().to("bob"); r.jenkins.setAuthorizationStrategy(strategy); HashMap<String, Authentication> jobsToUsers = new HashMap<String, Authentication>(); jobsToUsers.put(prj.getFullName(), User.get("bob").impersonate());
@Test public void sandboxInvokerUsed() throws Exception { jenkins.jenkins.setSecurityRealm(jenkins.createDummySecurityRealm()); jenkins.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.RUN_SCRIPTS, Jenkins.READ, Item.READ).everywhere().to("runScriptsUser"). grant(Jenkins.READ, Item.READ).everywhere().to("otherUser")); WorkflowJob job = jenkins.jenkins.createProject(WorkflowJob.class, "p"); job.setDefinition(new CpsFlowDefinition("[a: 1, b: 2].collectEntries { k, v ->\n" + " Jenkins.getInstance()\n" + " [(v): k]\n" + "}\n", true)); WorkflowRun r = jenkins.assertBuildStatus(Result.FAILURE, job.scheduleBuild2(0).get()); jenkins.assertLogContains("org.jenkinsci.plugins.scriptsecurity.sandbox.RejectedAccessException: Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance", r); jenkins.assertLogContains("Scripts not permitted to use staticMethod jenkins.model.Jenkins getInstance. " + Messages.SandboxContinuable_ScriptApprovalLink(), r); JenkinsRule.WebClient wc = jenkins.createWebClient(); wc.login("runScriptsUser"); // make sure we see the annotation for the RUN_SCRIPTS user. HtmlPage rsp = wc.getPage(r, "console"); assertEquals(1, DomNodeUtil.selectNodes(rsp, "//A[@href='" + jenkins.contextPath + "/scriptApproval']").size()); // make sure raw console output doesn't include the garbage and has the right message. TextPage raw = (TextPage)wc.goTo(r.getUrl()+"consoleText","text/plain"); assertThat(raw.getContent(), containsString(" getInstance. " + Messages.SandboxContinuable_ScriptApprovalLink())); wc.login("otherUser"); // make sure we don't see the link for the other user. HtmlPage rsp2 = wc.getPage(r, "console"); assertEquals(0, DomNodeUtil.selectNodes(rsp2, "//A[@href='" + jenkins.contextPath + "/scriptApproval']").size()); // make sure raw console output doesn't include the garbage and has the right message. TextPage raw2 = (TextPage)wc.goTo(r.getUrl()+"consoleText","text/plain"); assertThat(raw2.getContent(), containsString(" getInstance. " + Messages.SandboxContinuable_ScriptApprovalLink())); }
@Test public void given_folderCredential_when_builtAsUserWithUseItem_then_credentialFound() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "Dr. Fu Manchu", "foo", "manchu")); FreeStyleProject prj = f.createProject(FreeStyleProject.class, "job"); prj.getBuildersList().add(new HasCredentialBuilder("foo-manchu")); JenkinsRule.DummySecurityRealm realm = r.createDummySecurityRealm(); r.jenkins.setSecurityRealm(realm); MockAuthorizationStrategy strategy = new MockAuthorizationStrategy(); strategy.grant(CredentialsProvider.USE_ITEM).everywhere().to("bob"); strategy.grant(Item.BUILD).everywhere().to("bob"); strategy.grant(Computer.BUILD).everywhere().to("bob"); r.jenkins.setAuthorizationStrategy(strategy); HashMap<String, Authentication> jobsToUsers = new HashMap<String, Authentication>(); jobsToUsers.put(prj.getFullName(), User.get("bob").impersonate()); MockQueueItemAuthenticator authenticator = new MockQueueItemAuthenticator(jobsToUsers); QueueItemAuthenticatorConfiguration.get().getAuthenticators().clear(); QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(authenticator); r.buildAndAssertSuccess(prj); }
@Test public void given_folderCredential_when_builtAsUserWithoutUseItem_then_credentialNotFound() throws Exception { Folder f = createFolder(); CredentialsStore folderStore = getFolderStore(f); folderStore.addCredentials(Domain.global(), new UsernamePasswordCredentialsImpl(CredentialsScope.GLOBAL, "foo-manchu", "Dr. Fu Manchu", "foo", "manchu")); FreeStyleProject prj = f.createProject(FreeStyleProject.class, "job"); prj.getBuildersList().add(new HasCredentialBuilder("foo-manchu")); JenkinsRule.DummySecurityRealm realm = r.createDummySecurityRealm(); r.jenkins.setSecurityRealm(realm); MockAuthorizationStrategy strategy = new MockAuthorizationStrategy(); strategy.grant(Item.BUILD).everywhere().to("bob"); strategy.grant(Computer.BUILD).everywhere().to("bob"); r.jenkins.setAuthorizationStrategy(strategy); HashMap<String, Authentication> jobsToUsers = new HashMap<String, Authentication>(); jobsToUsers.put(prj.getFullName(), User.get("bob").impersonate()); MockQueueItemAuthenticator authenticator = new MockQueueItemAuthenticator(jobsToUsers); QueueItemAuthenticatorConfiguration.get().getAuthenticators().clear(); QueueItemAuthenticatorConfiguration.get().getAuthenticators().add(authenticator); r.assertBuildStatus(Result.FAILURE, prj.scheduleBuild2(0).get()); }
@Test public void discoverPermission() throws Exception { r.jenkins.setSecurityRealm(r.createDummySecurityRealm()); final Folder d = r.jenkins.createProject(Folder.class, "d"); final FreeStyleProject p1 = d.createProject(FreeStyleProject.class, "p1"); r.jenkins.setAuthorizationStrategy(new MockAuthorizationStrategy(). grant(Jenkins.READ).everywhere().toEveryone(). grant(Item.DISCOVER).everywhere().toAuthenticated(). grant(Item.READ).onItems(d).toEveryone(). grant(Item.READ).onItems(p1).to("alice")); FreeStyleProject p2 = d.createProject(FreeStyleProject.class, "p2"); ACL.impersonate(Jenkins.ANONYMOUS, new Runnable() { @Override public void run() { assertEquals(Collections.emptyList(), d.getItems()); assertNull(d.getItem("p1")); assertNull(d.getItem("p2")); } }); ACL.impersonate(User.get("alice").impersonate(), new Runnable() { @Override public void run() { assertEquals(Collections.singletonList(p1), d.getItems()); assertEquals(p1, d.getItem("p1")); try { d.getItem("p2"); fail("should have been told p2 exists"); } catch (AccessDeniedException x) { // correct } } }); }
/** * Tests that only an admin can read server configuration and manipulate server state. * @throws Exception if so */ @Test @Issue({"SECURITY-402", "SECURITY-403" }) public void testOnlyAdminCanPerformServerConfigurationActions() throws Exception { GerritServer gerritServer = new GerritServer(PluginImpl.DEFAULT_SERVER_NAME); SshdServerMock.configureFor(sshd, gerritServer); PluginImpl.getInstance().addServer(gerritServer); gerritServer.getConfig().setNumberOfSendingWorkerThreads(NUMBEROFSENDERTHREADS); ((Config)gerritServer.getConfig()).setGerritAuthKeyFile(sshKey.getPrivateKey()); gerritServer.start(); Setup.lockDown(j); j.getInstance().setAuthorizationStrategy( new MockAuthorizationStrategy().grant(Item.READ, Item.DISCOVER).everywhere().toAuthenticated() .grant(Jenkins.READ, Item.DISCOVER).everywhere().toEveryone() .grant(Item.CONFIGURE).everywhere().to("bob") .grant(Jenkins.ADMINISTER).everywhere().to("alice")); j.jenkins.setCrumbIssuer(null); //Not really testing csrf right now JenkinsRule.WebClient webClient = j.createWebClient().login("alice", "alice"); HtmlPage page = webClient.goTo("plugin/gerrit-trigger/servers/0/"); HtmlForm config = page.getFormByName("config"); assertNotNull(config); post(webClient, "plugin/gerrit-trigger/servers/0/sleep", "application/json", null); webClient = j.createWebClient().login("bob", "bob"); webClient.assertFails("plugin/gerrit-trigger/servers/0/", 403); post(webClient, "plugin/gerrit-trigger/servers/0/wakeup", null, 403); }