Search in sources :

Example 1 with AuthorisationException

use of com.atlassian.stash.exception.AuthorisationException in project stashbot by palantir.

the class JenkinsConfigurationServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    // Authenticate user
    try {
        permissionValidationService.validateAuthenticated();
    } catch (AuthorisationException notLoggedInException) {
        log.debug("User not logged in, redirecting to login page");
        // not logged in, redirect
        res.sendRedirect(lup.getLoginUri(getUri(req)).toASCIIString());
        return;
    }
    log.debug("User {} logged in", req.getRemoteUser());
    try {
        permissionValidationService.validateForGlobal(Permission.SYS_ADMIN);
    } catch (AuthorisationException notAdminException) {
        log.warn("User {} is not a system administrator", req.getRemoteUser());
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You do not have permission to access this page.");
        return;
    }
    // Handle deletes
    String pathInfo = req.getPathInfo();
    String relUrl = req.getRequestURL().toString();
    relUrl = relUrl.replaceAll("/+$", "").replaceAll("/delete/?.*$", "").replaceAll("/reload-all/?.*$", "").replaceAll("/create-new/?.*$", "").replaceAll("\\?notice=.*$", "").replaceAll("\\?error=.*$", "");
    String[] parts = pathInfo.replaceFirst(PATH_PREFIX, "").split("/");
    if (parts.length >= 2) {
        if (parts[1].equals("delete")) {
            log.info("Deleting configuration " + parts[2]);
            configurationPersistanceManager.deleteJenkinsServerConfiguration(parts[2]);
            res.sendRedirect(relUrl);
            return;
        }
        if (parts[1].equals("reload-all")) {
            jenkinsManager.updateAllJobs();
            res.sendRedirect(relUrl);
        }
        if (parts[1].equals("create-new")) {
            jenkinsManager.createMissingJobs();
            res.sendRedirect(relUrl);
        }
    }
    String error = req.getParameter("error");
    if (error == null) {
        error = new String();
    }
    String notice = req.getParameter("notice");
    if (notice == null) {
        notice = new String();
    }
    res.setContentType("text/html;charset=UTF-8");
    try {
        // Build select data for authentication modes
        // Structure is:  { "jenkinsServerName" => [ { "text" => "auth description", "value" => "auth code" }, { ... } ], ... }
        ImmutableMap.Builder<String, ImmutableList<ImmutableMap<String, String>>> authDataBuilder = ImmutableMap.builder();
        ImmutableMap.Builder<String, String> authDataSelectedBuilder = ImmutableMap.builder();
        for (JenkinsServerConfiguration jsc : configurationPersistanceManager.getAllJenkinsServerConfigurations()) {
            AuthenticationMode am = jsc.getAuthenticationMode();
            ImmutableList<ImmutableMap<String, String>> selectList = AuthenticationMode.getSelectList(am);
            authDataBuilder.put(jsc.getName(), selectList);
            // For convenience, store the value of the selected field in a separate map
            authDataSelectedBuilder.put(jsc.getName(), jsc.getAuthenticationMode().getSelectListEntry(false).get("value"));
        }
        pageBuilderService.assembler().resources().requireContext("plugin.page.stashbot");
        ImmutableCollection<JenkinsServerConfiguration> jenkinsConfigs = configurationPersistanceManager.getAllJenkinsServerConfigurations();
        soyTemplateRenderer.render(res.getWriter(), "com.palantir.stash.stashbot:stashbotConfigurationResources", "plugin.page.stashbot.jenkinsConfigurationPanel", ImmutableMap.<String, Object>builder().put("relUrl", relUrl).put("jenkinsConfigs", jenkinsConfigs).put("error", error).put("notice", notice).put("authenticationModeData", authDataBuilder.build()).put("authenticationModeDataSelected", authDataSelectedBuilder.build()).build());
    } catch (SoyException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw new ServletException(e);
        }
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}
Also used : SQLException(java.sql.SQLException) ImmutableList(com.google.common.collect.ImmutableList) SoyException(com.atlassian.soy.renderer.SoyException) IOException(java.io.IOException) ImmutableMap(com.google.common.collect.ImmutableMap) ServletException(javax.servlet.ServletException) AuthenticationMode(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration.AuthenticationMode) AuthorisationException(com.atlassian.stash.exception.AuthorisationException) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration)

Example 2 with AuthorisationException

use of com.atlassian.stash.exception.AuthorisationException in project stashbot by palantir.

the class RepoConfigurationServlet method doPost.

@Override
public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Repository rep = getRepository(req);
    if (rep == null) {
        log.error("Failed to get repo for request" + req.toString());
        res.sendError(404);
        return;
    }
    try {
        permissionValidationService.validateForRepository(rep, Permission.REPO_ADMIN);
    } catch (AuthorisationException notRepoAdmin) {
        // Skip form processing
        doGet(req, res);
        return;
    }
    try {
        // This is the new jenkins server name
        String jenkinsServerName = req.getParameter("jenkinsServerName");
        // If either the old or the new Jenkins Server Configuration is "locked", and we are trying to change it, then enforce SYS_ADMIN instead of REPO_ADMIN
        try {
            RepositoryConfiguration rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
            JenkinsServerConfiguration oldConfig = configurationPersistanceManager.getJenkinsServerConfiguration(rc.getJenkinsServerName());
            JenkinsServerConfiguration newConfig = configurationPersistanceManager.getJenkinsServerConfiguration(jenkinsServerName);
            if (!jenkinsServerName.equals(oldConfig.getName())) {
                if (oldConfig.getLocked()) {
                    permissionValidationService.validateForGlobal(Permission.SYS_ADMIN);
                }
                if (newConfig.getLocked()) {
                    permissionValidationService.validateForGlobal(Permission.SYS_ADMIN);
                }
            }
        } catch (AuthorisationException notSysAdmin) {
            // only thrown when oldconfig is locked and newconfig's name is different from oldconfig's name.
            log.warn("User {} tried to change the jenkins configuration which was locked for repo {}", req.getRemoteUser(), rep.getSlug());
            res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You do not have permission to change the jenkins server configuration");
            return;
        }
        configurationPersistanceManager.setRepositoryConfigurationForRepositoryFromRequest(rep, req);
        RepositoryConfiguration rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
        if (rc.getCiEnabled()) {
            // ensure all pull request metadata exists
            PullRequestSearchRequest prsr = new PullRequestSearchRequest.Builder().toRepositoryId(rep.getId()).build();
            PageRequest pageReq = new PageRequestImpl(0, 500);
            Page<PullRequest> page = prs.search(prsr, pageReq);
            while (true) {
                for (PullRequest pr : page.getValues()) {
                    // this auto-vivifies if it doesn't already exist
                    configurationPersistanceManager.getPullRequestMetadata(pr);
                }
                if (page.getIsLastPage()) {
                    break;
                }
                pageReq = page.getNextPageRequest();
                page = prs.search(prsr, pageReq);
            }
            // add permission to the requisite user
            JenkinsServerConfiguration jsc = configurationPersistanceManager.getJenkinsServerConfiguration(jenkinsServerName);
            pluginUserManager.addUserToRepoForReading(jsc.getStashUsername(), rep);
            // ensure hook is enabled, jobs exist
            jenkinsManager.updateRepo(rep);
        }
    } catch (SQLException e) {
        log.error("Unable to get repository confguration", e);
    }
    doGet(req, res);
}
Also used : Repository(com.atlassian.stash.repository.Repository) PageRequest(com.atlassian.stash.util.PageRequest) SQLException(java.sql.SQLException) PullRequest(com.atlassian.stash.pull.PullRequest) PageRequestImpl(com.atlassian.stash.util.PageRequestImpl) AuthorisationException(com.atlassian.stash.exception.AuthorisationException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) PullRequestSearchRequest(com.atlassian.stash.pull.PullRequestSearchRequest)

Example 3 with AuthorisationException

use of com.atlassian.stash.exception.AuthorisationException in project stashbot by palantir.

the class RepoConfigurationServlet method doGet.

@Override
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    Repository rep = getRepository(req);
    if (rep == null) {
        res.sendError(404);
        return;
    }
    try {
        permissionValidationService.validateForRepository(rep, Permission.REPO_ADMIN);
    } catch (AuthorisationException notRepoAdmin) {
        log.warn("User {} tried to access the stashbot admin page for {}", req.getRemoteUser(), rep.getSlug());
        res.sendError(HttpServletResponse.SC_UNAUTHORIZED, "You do not have permission to access this page.");
        return;
    }
    RepositoryConfiguration rc;
    JenkinsServerConfiguration theJsc;
    try {
        rc = configurationPersistanceManager.getRepositoryConfigurationForRepository(rep);
        theJsc = configurationPersistanceManager.getJenkinsServerConfiguration(rc.getJenkinsServerName());
    } catch (SQLException e1) {
        throw new ServletException(e1);
    }
    res.setContentType("text/html;charset=UTF-8");
    try {
        List<Map<String, String>> jenkinsServersData = new ArrayList<Map<String, String>>();
        for (JenkinsServerConfiguration jsc : configurationPersistanceManager.getAllJenkinsServerConfigurations()) {
            HashMap<String, String> m = new HashMap<String, String>();
            m.put("text", jsc.getName());
            m.put("value", jsc.getName());
            if (rc.getJenkinsServerName().equals(jsc.getName())) {
                m.put("selected", "true");
            }
            jenkinsServersData.add(m);
        }
        pageBuilderService.assembler().resources().requireContext("plugin.page.stashbot");
        pageBuilderService.assembler().resources().requireWebResource("com.palantir.stash.stashbot:stashbot-resources");
        soyTemplateRenderer.render(res.getWriter(), "com.palantir.stash.stashbot:stashbotConfigurationResources", "plugin.page.stashbot.repositoryConfigurationPanel", ImmutableMap.<String, Object>builder().put("repository", rep).put("ciEnabled", rc.getCiEnabled()).put("publishBranchRegex", rc.getPublishBranchRegex()).put("publishBuildCommand", rc.getPublishBuildCommand()).put("verifyBranchRegex", rc.getVerifyBranchRegex()).put("verifyBuildCommand", rc.getVerifyBuildCommand()).put("prebuildCommand", rc.getPrebuildCommand()).put("jenkinsServerName", rc.getJenkinsServerName()).put("maxVerifyChain", rc.getMaxVerifyChain().toString()).put("rebuildOnUpdate", rc.getRebuildOnTargetUpdate()).put("isVerifyPinned", rc.getVerifyPinned()).put("verifyLabel", rc.getVerifyLabel()).put("isPublishPinned", rc.getPublishPinned()).put("publishLabel", rc.getPublishLabel()).put("isJunit", rc.getJunitEnabled()).put("junitPath", rc.getJunitPath()).put("artifactsEnabled", rc.getArtifactsEnabled()).put("artifactsPath", rc.getArtifactsPath()).put("jenkinsServersData", jenkinsServersData).put("isEmailNotificationsEnabled", rc.getEmailNotificationsEnabled()).put("isEmailForEveryUnstableBuild", rc.getEmailForEveryUnstableBuild()).put("isEmailPerModuleEmail", rc.getEmailPerModuleEmail()).put("emailRecipients", rc.getEmailRecipients()).put("isEmailSendToIndividuals", rc.getEmailSendToIndividuals()).put("isStrictVerifyMode", rc.getStrictVerifyMode()).put("isPreserveJenkinsJobConfig", rc.getPreserveJenkinsJobConfig()).put("isLocked", isLocked(theJsc)).put("verificationEnabled", configurationPersistanceManager.getJobTypeStatusMapping(rc, JobType.VERIFY_COMMIT)).put("verifyPREnabled", configurationPersistanceManager.getJobTypeStatusMapping(rc, JobType.VERIFY_PR)).put("publishEnabled", configurationPersistanceManager.getJobTypeStatusMapping(rc, JobType.PUBLISH)).build());
    } catch (SoyException e) {
        Throwable cause = e.getCause();
        if (cause instanceof IOException) {
            throw (IOException) cause;
        } else {
            throw new ServletException(e);
        }
    } catch (SQLException e) {
        throw new ServletException(e);
    }
}
Also used : SQLException(java.sql.SQLException) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) SoyException(com.atlassian.soy.renderer.SoyException) IOException(java.io.IOException) ServletException(javax.servlet.ServletException) Repository(com.atlassian.stash.repository.Repository) AuthorisationException(com.atlassian.stash.exception.AuthorisationException) RepositoryConfiguration(com.palantir.stash.stashbot.persistence.RepositoryConfiguration) JenkinsServerConfiguration(com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration) HashMap(java.util.HashMap) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap)

Example 4 with AuthorisationException

use of com.atlassian.stash.exception.AuthorisationException in project stashbot by palantir.

the class JenkinsConfigurationServletTest method getTestWhenNotSysAdmin.

@Test
public void getTestWhenNotSysAdmin() throws Exception {
    when(req.getRemoteUser()).thenReturn("nonAdminStashUser");
    doThrow(new AuthorisationException(new KeyedMessage("testException", "testException", "testException"))).when(pvs).validateForGlobal(Permission.SYS_ADMIN);
    jcs.doGet(req, res);
    verify(res).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED), any(String.class));
}
Also used : AuthorisationException(com.atlassian.stash.exception.AuthorisationException) KeyedMessage(com.atlassian.stash.i18n.KeyedMessage) Test(org.junit.Test)

Example 5 with AuthorisationException

use of com.atlassian.stash.exception.AuthorisationException in project stashbot by palantir.

the class RepoConfigurationServletTest method getTestWhenNotRepoAdmin.

@Test
public void getTestWhenNotRepoAdmin() throws Exception {
    doThrow(new AuthorisationException(new KeyedMessage("testException", "testException", "testException"))).when(pvs).validateForRepository(Mockito.any(Repository.class), eq(Permission.REPO_ADMIN));
    rcs.doGet(req, res);
    verify(res).sendError(eq(HttpServletResponse.SC_UNAUTHORIZED), Mockito.any(String.class));
}
Also used : Repository(com.atlassian.stash.repository.Repository) AuthorisationException(com.atlassian.stash.exception.AuthorisationException) KeyedMessage(com.atlassian.stash.i18n.KeyedMessage) Test(org.junit.Test)

Aggregations

AuthorisationException (com.atlassian.stash.exception.AuthorisationException)12 KeyedMessage (com.atlassian.stash.i18n.KeyedMessage)7 Test (org.junit.Test)7 Repository (com.atlassian.stash.repository.Repository)5 ImmutableMap (com.google.common.collect.ImmutableMap)3 JenkinsServerConfiguration (com.palantir.stash.stashbot.persistence.JenkinsServerConfiguration)3 IOException (java.io.IOException)3 SQLException (java.sql.SQLException)3 ServletException (javax.servlet.ServletException)3 SoyException (com.atlassian.soy.renderer.SoyException)2 PageRequest (com.atlassian.stash.util.PageRequest)2 PageRequestImpl (com.atlassian.stash.util.PageRequestImpl)2 RepositoryConfiguration (com.palantir.stash.stashbot.persistence.RepositoryConfiguration)2 ArrayList (java.util.ArrayList)2 HashMap (java.util.HashMap)2 PullRequest (com.atlassian.stash.pull.PullRequest)1 PullRequestSearchRequest (com.atlassian.stash.pull.PullRequestSearchRequest)1 ImmutableList (com.google.common.collect.ImmutableList)1 ImmutableSet (com.google.common.collect.ImmutableSet)1 GlobalSettings (com.palantir.stash.codesearch.admin.GlobalSettings)1