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);
}
}
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);
}
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);
}
}
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));
}
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));
}
Aggregations