use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class RunAsFilter method doFilter.
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpServletResponse res = (HttpServletResponse) response;
String runas = req.getHeader(RUN_AS);
if (runas != null) {
if (!enabled) {
replyError(req, res, SC_FORBIDDEN, RUN_AS + " disabled by auth.enableRunAs = false", null);
return;
}
CurrentUser self = session.get().getUser();
try {
if (!self.isIdentifiedUser()) {
// because that would be crazy.
throw new AuthException("denied");
}
permissionBackend.user(self).check(GlobalPermission.RUN_AS);
} catch (AuthException e) {
replyError(req, res, SC_FORBIDDEN, "not permitted to use " + RUN_AS, null);
return;
} catch (PermissionBackendException e) {
log.warn("cannot check runAs", e);
replyError(req, res, SC_INTERNAL_SERVER_ERROR, RUN_AS + " unavailable", null);
return;
}
Account target;
try {
target = accountResolver.find(db.get(), runas);
} catch (OrmException e) {
log.warn("cannot resolve account for " + RUN_AS, e);
replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e);
return;
}
if (target == null) {
replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null);
return;
}
session.get().setUserAccountId(target.getId());
}
chain.doFilter(req, res);
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class RestApiServlet method service.
@Override
protected final void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
final long startNanos = System.nanoTime();
long auditStartTs = TimeUtil.nowMs();
res.setHeader("Content-Disposition", "attachment");
res.setHeader("X-Content-Type-Options", "nosniff");
int status = SC_OK;
long responseBytes = -1;
Object result = null;
ListMultimap<String, String> params = MultimapBuilder.hashKeys().arrayListValues().build();
ListMultimap<String, String> config = MultimapBuilder.hashKeys().arrayListValues().build();
Object inputRequestBody = null;
RestResource rsrc = TopLevelResource.INSTANCE;
ViewData viewData = null;
try {
if (isCorsPreflight(req)) {
doCorsPreflight(req, res);
return;
}
checkCors(req, res);
checkUserSession(req);
ParameterParser.splitQueryString(req.getQueryString(), config, params);
List<IdString> path = splitPath(req);
RestCollection<RestResource, RestResource> rc = members.get();
globals.permissionBackend.user(globals.currentUser).checkAny(GlobalPermission.fromAnnotation(rc.getClass()));
viewData = new ViewData(null, null);
if (path.isEmpty()) {
if (rc instanceof NeedsParams) {
((NeedsParams) rc).setParams(params);
}
if (isRead(req)) {
viewData = new ViewData(null, rc.list());
} else if (rc instanceof AcceptsPost && "POST".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) rc;
viewData = new ViewData(null, ac.post(rsrc));
} else {
throw new MethodNotAllowedException();
}
} else {
IdString id = path.remove(0);
try {
rsrc = rc.parse(rsrc, id);
if (path.isEmpty()) {
checkPreconditions(req);
}
} catch (ResourceNotFoundException e) {
if (rc instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) {
@SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) rc;
viewData = new ViewData(null, ac.create(rsrc, id));
status = SC_CREATED;
} else {
throw e;
}
}
if (viewData.view == null) {
viewData = view(rsrc, rc, req.getMethod(), path);
}
}
checkRequiresCapability(viewData);
while (viewData.view instanceof RestCollection<?, ?>) {
@SuppressWarnings("unchecked") RestCollection<RestResource, RestResource> c = (RestCollection<RestResource, RestResource>) viewData.view;
if (path.isEmpty()) {
if (isRead(req)) {
viewData = new ViewData(null, c.list());
} else if (c instanceof AcceptsPost && "POST".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsPost<RestResource> ac = (AcceptsPost<RestResource>) c;
viewData = new ViewData(null, ac.post(rsrc));
} else if (c instanceof AcceptsDelete && "DELETE".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c;
viewData = new ViewData(null, ac.delete(rsrc, null));
} else {
throw new MethodNotAllowedException();
}
break;
}
IdString id = path.remove(0);
try {
rsrc = c.parse(rsrc, id);
checkPreconditions(req);
viewData = new ViewData(null, null);
} catch (ResourceNotFoundException e) {
if (c instanceof AcceptsCreate && path.isEmpty() && ("POST".equals(req.getMethod()) || "PUT".equals(req.getMethod()))) {
@SuppressWarnings("unchecked") AcceptsCreate<RestResource> ac = (AcceptsCreate<RestResource>) c;
viewData = new ViewData(viewData.pluginName, ac.create(rsrc, id));
status = SC_CREATED;
} else if (c instanceof AcceptsDelete && path.isEmpty() && "DELETE".equals(req.getMethod())) {
@SuppressWarnings("unchecked") AcceptsDelete<RestResource> ac = (AcceptsDelete<RestResource>) c;
viewData = new ViewData(viewData.pluginName, ac.delete(rsrc, id));
status = SC_NO_CONTENT;
} else {
throw e;
}
}
if (viewData.view == null) {
viewData = view(rsrc, c, req.getMethod(), path);
}
checkRequiresCapability(viewData);
}
if (notModified(req, rsrc, viewData.view)) {
res.sendError(SC_NOT_MODIFIED);
return;
}
if (!globals.paramParser.get().parse(viewData.view, params, req, res)) {
return;
}
if (viewData.view instanceof RestReadView<?> && isRead(req)) {
result = ((RestReadView<RestResource>) viewData.view).apply(rsrc);
} else if (viewData.view instanceof RestModifyView<?, ?>) {
@SuppressWarnings("unchecked") RestModifyView<RestResource, Object> m = (RestModifyView<RestResource, Object>) viewData.view;
Type type = inputType(m);
inputRequestBody = parseRequest(req, type);
result = m.apply(rsrc, inputRequestBody);
consumeRawInputRequestBody(req, type);
} else {
throw new ResourceNotFoundException();
}
if (result instanceof Response) {
@SuppressWarnings("rawtypes") Response<?> r = (Response) result;
status = r.statusCode();
configureCaching(req, res, rsrc, viewData.view, r.caching());
} else if (result instanceof Response.Redirect) {
CacheHeaders.setNotCacheable(res);
res.sendRedirect(((Response.Redirect) result).location());
return;
} else if (result instanceof Response.Accepted) {
CacheHeaders.setNotCacheable(res);
res.setStatus(SC_ACCEPTED);
res.setHeader(HttpHeaders.LOCATION, ((Response.Accepted) result).location());
return;
} else {
CacheHeaders.setNotCacheable(res);
}
res.setStatus(status);
if (result != Response.none()) {
result = Response.unwrap(result);
if (result instanceof BinaryResult) {
responseBytes = replyBinaryResult(req, res, (BinaryResult) result);
} else {
responseBytes = replyJson(req, res, config, result);
}
}
} catch (MalformedJsonException e) {
responseBytes = replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e);
} catch (JsonParseException e) {
responseBytes = replyError(req, res, status = SC_BAD_REQUEST, "Invalid " + JSON_TYPE + " in request", e);
} catch (BadRequestException e) {
responseBytes = replyError(req, res, status = SC_BAD_REQUEST, messageOr(e, "Bad Request"), e.caching(), e);
} catch (AuthException e) {
responseBytes = replyError(req, res, status = SC_FORBIDDEN, messageOr(e, "Forbidden"), e.caching(), e);
} catch (AmbiguousViewException e) {
responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Ambiguous"), e);
} catch (ResourceNotFoundException e) {
responseBytes = replyError(req, res, status = SC_NOT_FOUND, messageOr(e, "Not Found"), e.caching(), e);
} catch (MethodNotAllowedException e) {
responseBytes = replyError(req, res, status = SC_METHOD_NOT_ALLOWED, messageOr(e, "Method Not Allowed"), e.caching(), e);
} catch (ResourceConflictException e) {
responseBytes = replyError(req, res, status = SC_CONFLICT, messageOr(e, "Conflict"), e.caching(), e);
} catch (PreconditionFailedException e) {
responseBytes = replyError(req, res, status = SC_PRECONDITION_FAILED, messageOr(e, "Precondition Failed"), e.caching(), e);
} catch (UnprocessableEntityException e) {
responseBytes = replyError(req, res, status = SC_UNPROCESSABLE_ENTITY, messageOr(e, "Unprocessable Entity"), e.caching(), e);
} catch (NotImplementedException e) {
responseBytes = replyError(req, res, status = SC_NOT_IMPLEMENTED, messageOr(e, "Not Implemented"), e);
} catch (Exception e) {
status = SC_INTERNAL_SERVER_ERROR;
responseBytes = handleException(e, req, res);
} finally {
String metric = viewData != null && viewData.view != null ? globals.metrics.view(viewData) : "_unknown";
globals.metrics.count.increment(metric);
if (status >= SC_BAD_REQUEST) {
globals.metrics.errorCount.increment(metric, status);
}
if (responseBytes != -1) {
globals.metrics.responseBytes.record(metric, responseBytes);
}
globals.metrics.serverLatency.record(metric, System.nanoTime() - startNanos, TimeUnit.NANOSECONDS);
globals.auditService.dispatch(new ExtendedHttpAuditEvent(globals.webSession.get().getSessionId(), globals.currentUser.get(), req, auditStartTs, params, inputRequestBody, status, result, rsrc, viewData == null ? null : viewData.view));
}
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class GitwebServlet method service.
@Override
protected void service(final HttpServletRequest req, final HttpServletResponse rsp) throws IOException {
if (req.getQueryString() == null || req.getQueryString().isEmpty()) {
// No query string? They want the project list, which we don't
// currently support. Return to Gerrit's own web UI.
//
rsp.sendRedirect(req.getContextPath() + "/");
return;
}
final Map<String, String> params = getParameters(req);
String a = params.get("a");
if (a != null) {
if (deniedActions.contains(a)) {
rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
return;
}
if (a.equals(PROJECT_LIST_ACTION)) {
rsp.sendRedirect(req.getContextPath() + "/#" + PageLinks.ADMIN_PROJECTS + "?filter=" + Url.encode(params.get("pf") + "/"));
return;
}
}
String name = params.get("p");
if (name == null) {
rsp.sendError(HttpServletResponse.SC_NOT_FOUND);
return;
}
if (name.endsWith(".git")) {
name = name.substring(0, name.length() - 4);
}
Project.NameKey nameKey = new Project.NameKey(name);
try {
if (projectCache.checkedGet(nameKey) == null) {
notFound(req, rsp);
return;
}
permissionBackend.user(userProvider).project(nameKey).check(ProjectPermission.READ);
} catch (AuthException e) {
notFound(req, rsp);
return;
} catch (IOException | PermissionBackendException err) {
log.error("cannot load " + name, err);
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
return;
}
try (Repository repo = repoManager.openRepository(nameKey)) {
CacheHeaders.setNotCacheable(rsp);
exec(req, rsp, nameKey);
} catch (RepositoryNotFoundException e) {
getServletContext().log("Cannot open repository", e);
rsp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
}
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class CherryPick method applyImpl.
@Override
protected ChangeInfo applyImpl(BatchUpdate.Factory updateFactory, RevisionResource revision, CherryPickInput input) throws OrmException, IOException, UpdateException, RestApiException {
final ChangeControl control = revision.getControl();
input.parent = input.parent == null ? 1 : input.parent;
if (input.message == null || input.message.trim().isEmpty()) {
throw new BadRequestException("message must be non-empty");
} else if (input.destination == null || input.destination.trim().isEmpty()) {
throw new BadRequestException("destination must be non-empty");
}
if (!control.isVisible(dbProvider.get())) {
throw new AuthException("Cherry pick not permitted");
}
ProjectControl projectControl = control.getProjectControl();
Capable capable = projectControl.canPushToAtLeastOneRef();
if (capable != Capable.OK) {
throw new AuthException(capable.getMessage());
}
String refName = RefNames.fullName(input.destination);
RefControl refControl = projectControl.controlForRef(refName);
if (!refControl.canUpload()) {
throw new AuthException("Not allowed to cherry pick " + revision.getChange().getId().toString() + " to " + input.destination);
}
try {
Change.Id cherryPickedChangeId = cherryPickChange.cherryPick(updateFactory, revision.getChange(), revision.getPatchSet(), input, refName, refControl);
return json.noOptions().format(revision.getProject(), cherryPickedChangeId);
} catch (InvalidChangeOperationException e) {
throw new BadRequestException(e.getMessage());
} catch (IntegrationException | NoSuchChangeException e) {
throw new ResourceConflictException(e.getMessage());
}
}
use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.
the class DeleteIncludedGroups method apply.
@Override
public Response<?> apply(GroupResource resource, Input input) throws AuthException, MethodNotAllowedException, UnprocessableEntityException, OrmException {
AccountGroup internalGroup = resource.toAccountGroup();
if (internalGroup == null) {
throw new MethodNotAllowedException();
}
input = Input.init(input);
final GroupControl control = resource.getControl();
final Map<AccountGroup.UUID, AccountGroupById> includedGroups = getIncludedGroups(internalGroup.getId());
final List<AccountGroupById> toRemove = new ArrayList<>();
for (final String includedGroup : input.groups) {
GroupDescription.Basic d = groupsCollection.parse(includedGroup);
if (!control.canRemoveGroup()) {
throw new AuthException(String.format("Cannot delete group: %s", d.getName()));
}
AccountGroupById g = includedGroups.remove(d.getGroupUUID());
if (g != null) {
toRemove.add(g);
}
}
if (!toRemove.isEmpty()) {
writeAudits(toRemove);
db.get().accountGroupById().delete(toRemove);
for (final AccountGroupById g : toRemove) {
groupIncludeCache.evictParentGroupsOf(g.getIncludeUUID());
}
groupIncludeCache.evictSubgroupsOf(internalGroup.getGroupUUID());
}
return Response.none();
}
Aggregations