Search in sources :

Example 11 with PermissionBackendException

use of com.google.gerrit.server.permissions.PermissionBackendException in project gerrit by GerritCodeReview.

the class PRED__user_label_range_4 method exec.

@Override
public Operation exec(Prolog engine) throws PrologException {
    engine.setB0();
    Term a1 = arg1.dereference();
    Term a2 = arg2.dereference();
    Term a3 = arg3.dereference();
    Term a4 = arg4.dereference();
    if (a1 instanceof VariableTerm) {
        throw new PInstantiationException(this, 1);
    }
    if (!(a1 instanceof SymbolTerm)) {
        throw new IllegalTypeException(this, 1, "atom", a1);
    }
    String label = a1.name();
    if (a2 instanceof VariableTerm) {
        throw new PInstantiationException(this, 2);
    }
    if (!(a2 instanceof JavaObjectTerm) || !a2.convertible(CurrentUser.class)) {
        throw new IllegalTypeException(this, 2, "CurrentUser)", a2);
    }
    CurrentUser user = (CurrentUser) ((JavaObjectTerm) a2).object();
    Set<LabelPermission.WithValue> can;
    try {
        ChangeData cd = StoredValues.CHANGE_DATA.get(engine);
        LabelType type = cd.getLabelTypes().byLabel(label);
        if (type == null) {
            return engine.fail();
        }
        can = StoredValues.PERMISSION_BACKEND.get(engine).user(user).change(cd).test(type);
    } catch (OrmException err) {
        throw new JavaException(this, 1, err);
    } catch (PermissionBackendException err) {
        SystemException se = new SystemException(err.getMessage());
        se.initCause(err);
        throw se;
    }
    int min = 0;
    int max = 0;
    for (LabelPermission.WithValue v : can) {
        min = Math.min(min, v.value());
        max = Math.max(max, v.value());
    }
    if (!a3.unify(new IntegerTerm(min), engine.trail)) {
        return engine.fail();
    }
    if (!a4.unify(new IntegerTerm(max), engine.trail)) {
        return engine.fail();
    }
    return cont;
}
Also used : JavaException(com.googlecode.prolog_cafe.exceptions.JavaException) IntegerTerm(com.googlecode.prolog_cafe.lang.IntegerTerm) IllegalTypeException(com.googlecode.prolog_cafe.exceptions.IllegalTypeException) CurrentUser(com.google.gerrit.server.CurrentUser) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Term(com.googlecode.prolog_cafe.lang.Term) IntegerTerm(com.googlecode.prolog_cafe.lang.IntegerTerm) JavaObjectTerm(com.googlecode.prolog_cafe.lang.JavaObjectTerm) SymbolTerm(com.googlecode.prolog_cafe.lang.SymbolTerm) VariableTerm(com.googlecode.prolog_cafe.lang.VariableTerm) ChangeData(com.google.gerrit.server.query.change.ChangeData) PInstantiationException(com.googlecode.prolog_cafe.exceptions.PInstantiationException) SystemException(com.googlecode.prolog_cafe.exceptions.SystemException) OrmException(com.google.gwtorm.server.OrmException) LabelType(com.google.gerrit.common.data.LabelType) JavaObjectTerm(com.googlecode.prolog_cafe.lang.JavaObjectTerm) VariableTerm(com.googlecode.prolog_cafe.lang.VariableTerm) LabelPermission(com.google.gerrit.server.permissions.LabelPermission)

Example 12 with PermissionBackendException

use of com.google.gerrit.server.permissions.PermissionBackendException 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);
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) Account(com.google.gerrit.reviewdb.client.Account) CurrentUser(com.google.gerrit.server.CurrentUser) OrmException(com.google.gwtorm.server.OrmException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(com.google.gerrit.extensions.restapi.AuthException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException)

Example 13 with PermissionBackendException

use of com.google.gerrit.server.permissions.PermissionBackendException 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);
    }
}
Also used : Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) AuthException(com.google.gerrit.extensions.restapi.AuthException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IOException(java.io.IOException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException)

Example 14 with PermissionBackendException

use of com.google.gerrit.server.permissions.PermissionBackendException in project gerrit by GerritCodeReview.

the class ReceiveCommits method processCommands.

void processCommands(Collection<ReceiveCommand> commands, MultiProgressMonitor progress) {
    newProgress = progress.beginSubTask("new", UNKNOWN);
    replaceProgress = progress.beginSubTask("updated", UNKNOWN);
    closeProgress = progress.beginSubTask("closed", UNKNOWN);
    commandProgress = progress.beginSubTask("refs", UNKNOWN);
    try {
        parseCommands(commands);
    } catch (PermissionBackendException err) {
        for (ReceiveCommand cmd : actualCommands) {
            if (cmd.getResult() == NOT_ATTEMPTED) {
                cmd.setResult(REJECTED_OTHER_REASON, "internal server error");
            }
        }
        logError(String.format("Failed to process refs in %s", project.getName()), err);
    }
    if (magicBranch != null && magicBranch.cmd.getResult() == NOT_ATTEMPTED) {
        selectNewAndReplacedChangesFromMagicBranch();
    }
    preparePatchSetsForReplace();
    insertChangesAndPatchSets();
    newProgress.end();
    replaceProgress.end();
    if (!errors.isEmpty()) {
        logDebug("Handling error conditions: {}", errors.keySet());
        for (Error error : errors.keySet()) {
            rp.sendMessage(buildError(error, errors.get(error)));
        }
        rp.sendMessage(String.format("User: %s", displayName(user)));
        rp.sendMessage(COMMAND_REJECTION_MESSAGE_FOOTER);
    }
    Set<Branch.NameKey> branches = new HashSet<>();
    for (ReceiveCommand c : actualCommands) {
        // involve kicking off an additional BatchUpdate.
        if (c.getResult() != OK) {
            continue;
        }
        if (isHead(c) || isConfig(c)) {
            switch(c.getType()) {
                case CREATE:
                case UPDATE:
                case UPDATE_NONFASTFORWARD:
                    autoCloseChanges(c);
                    branches.add(new Branch.NameKey(project.getNameKey(), c.getRefName()));
                    break;
                case DELETE:
                    break;
            }
        }
    }
    // Update superproject gitlinks if required.
    if (!branches.isEmpty()) {
        try (MergeOpRepoManager orm = ormProvider.get()) {
            orm.setContext(db, TimeUtil.nowTs(), user, receiveId);
            SubmoduleOp op = subOpFactory.create(branches, orm);
            op.updateSuperProjects(batchUpdateFactory);
        } catch (SubmoduleException e) {
            logError("Can't update the superprojects", e);
        }
    }
    closeProgress.end();
    commandProgress.end();
    progress.end();
    reportMessages();
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) HashSet(java.util.HashSet)

Example 15 with PermissionBackendException

use of com.google.gerrit.server.permissions.PermissionBackendException in project gerrit by GerritCodeReview.

the class ReceiveCommits method autoCloseChanges.

private void autoCloseChanges(final ReceiveCommand cmd) {
    logDebug("Starting auto-closing of changes");
    String refName = cmd.getRefName();
    checkState(!MagicBranch.isMagicBranch(refName), "shouldn't be auto-closing changes on magic branch %s", refName);
    // insertChangesAndPatchSets.
    try (BatchUpdate bu = batchUpdateFactory.create(db, projectControl.getProject().getNameKey(), user, TimeUtil.nowTs());
        ObjectInserter ins = repo.newObjectInserter();
        ObjectReader reader = ins.newReader();
        RevWalk rw = new RevWalk(reader)) {
        bu.setRepository(repo, rw, ins).updateChangesInParallel();
        bu.setRequestId(receiveId);
        // TODO(dborowitz): Teach BatchUpdate to ignore missing changes.
        RevCommit newTip = rw.parseCommit(cmd.getNewId());
        Branch.NameKey branch = new Branch.NameKey(project.getNameKey(), refName);
        rw.reset();
        rw.markStart(newTip);
        if (!ObjectId.zeroId().equals(cmd.getOldId())) {
            rw.markUninteresting(rw.parseCommit(cmd.getOldId()));
        }
        ListMultimap<ObjectId, Ref> byCommit = changeRefsById();
        Map<Change.Key, ChangeNotes> byKey = null;
        List<ReplaceRequest> replaceAndClose = new ArrayList<>();
        int existingPatchSets = 0;
        int newPatchSets = 0;
        COMMIT: for (RevCommit c; (c = rw.next()) != null; ) {
            rw.parseBody(c);
            for (Ref ref : byCommit.get(c.copy())) {
                existingPatchSets++;
                PatchSet.Id psId = PatchSet.Id.fromRef(ref.getName());
                bu.addOp(psId.getParentKey(), mergedByPushOpFactory.create(requestScopePropagator, psId, refName));
                continue COMMIT;
            }
            for (String changeId : c.getFooterLines(CHANGE_ID)) {
                if (byKey == null) {
                    byKey = openChangesByBranch(branch);
                }
                ChangeNotes onto = byKey.get(new Change.Key(changeId.trim()));
                if (onto != null) {
                    newPatchSets++;
                    // Hold onto this until we're done with the walk, as the call to
                    // req.validate below calls isMergedInto which resets the walk.
                    ReplaceRequest req = new ReplaceRequest(onto.getChangeId(), c, cmd, false);
                    req.notes = onto;
                    replaceAndClose.add(req);
                    continue COMMIT;
                }
            }
        }
        for (final ReplaceRequest req : replaceAndClose) {
            Change.Id id = req.notes.getChangeId();
            if (!req.validate(true)) {
                logDebug("Not closing {} because validation failed", id);
                continue;
            }
            req.addOps(bu, null);
            bu.addOp(id, mergedByPushOpFactory.create(requestScopePropagator, req.psId, refName).setPatchSetProvider(new Provider<PatchSet>() {

                @Override
                public PatchSet get() {
                    return req.replaceOp.getPatchSet();
                }
            }));
            bu.addOp(id, new ChangeProgressOp(closeProgress));
        }
        logDebug("Auto-closing {} changes with existing patch sets and {} with new patch sets", existingPatchSets, newPatchSets);
        bu.execute();
    } catch (RestApiException e) {
        logError("Can't insert patchset", e);
    } catch (IOException | OrmException | UpdateException | PermissionBackendException e) {
        logError("Can't scan for changes to close", e);
    }
}
Also used : ArrayList(java.util.ArrayList) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) OrmException(com.google.gwtorm.server.OrmException) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) ObjectReader(org.eclipse.jgit.lib.ObjectReader) UpdateException(com.google.gerrit.server.update.UpdateException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) ObjectId(org.eclipse.jgit.lib.ObjectId) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) Change(com.google.gerrit.reviewdb.client.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Provider(com.google.inject.Provider) Ref(org.eclipse.jgit.lib.Ref) RequestId(com.google.gerrit.server.util.RequestId) ObjectId(org.eclipse.jgit.lib.ObjectId) RevId(com.google.gerrit.reviewdb.client.RevId) RestApiException(com.google.gerrit.extensions.restapi.RestApiException)

Aggregations

PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)23 IOException (java.io.IOException)13 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 OrmException (com.google.gwtorm.server.OrmException)12 Project (com.google.gerrit.reviewdb.client.Project)10 CurrentUser (com.google.gerrit.server.CurrentUser)7 ChangeData (com.google.gerrit.server.query.change.ChangeData)7 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)6 RestApiException (com.google.gerrit.extensions.restapi.RestApiException)6 Change (com.google.gerrit.reviewdb.client.Change)6 ArrayList (java.util.ArrayList)6 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)5 HashSet (java.util.HashSet)5 MoreObjects (com.google.common.base.MoreObjects)4 Strings (com.google.common.base.Strings)4 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)4 ChangeNotes (com.google.gerrit.server.notedb.ChangeNotes)4 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)4 Inject (com.google.inject.Inject)4 Provider (com.google.inject.Provider)4