Search in sources :

Example 1 with RefControl

use of com.google.gerrit.server.project.RefControl in project gerrit by GerritCodeReview.

the class CherryPickCommit method applyImpl.

@Override
public ChangeInfo applyImpl(BatchUpdate.Factory updateFactory, CommitResource rsrc, CherryPickInput input) throws OrmException, IOException, UpdateException, RestApiException {
    RevCommit commit = rsrc.getCommit();
    String message = Strings.nullToEmpty(input.message).trim();
    input.message = message.isEmpty() ? commit.getFullMessage() : message;
    String destination = Strings.nullToEmpty(input.destination).trim();
    input.parent = input.parent == null ? 1 : input.parent;
    if (destination.isEmpty()) {
        throw new BadRequestException("destination must be non-empty");
    }
    ProjectControl projectControl = rsrc.getProject();
    Capable capable = projectControl.canPushToAtLeastOneRef();
    if (capable != Capable.OK) {
        throw new AuthException(capable.getMessage());
    }
    String refName = RefNames.fullName(destination);
    RefControl refControl = projectControl.controlForRef(refName);
    if (!refControl.canUpload()) {
        throw new AuthException("Not allowed to cherry pick " + commit + " to " + destination);
    }
    Project.NameKey project = projectControl.getProject().getNameKey();
    try {
        Change.Id cherryPickedChangeId = cherryPickChange.cherryPick(updateFactory, null, null, null, null, project, commit, input, refName, refControl);
        return json.noOptions().format(project, cherryPickedChangeId);
    } catch (InvalidChangeOperationException e) {
        throw new BadRequestException(e.getMessage());
    } catch (IntegrationException e) {
        throw new ResourceConflictException(e.getMessage());
    }
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) IntegrationException(com.google.gerrit.server.git.IntegrationException) RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Change(com.google.gerrit.reviewdb.client.Change) ProjectControl(com.google.gerrit.server.project.ProjectControl) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Capable(com.google.gerrit.common.data.Capable) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 2 with RefControl

use of com.google.gerrit.server.project.RefControl in project gerrit by GerritCodeReview.

the class CreateChange method applyImpl.

@Override
protected Response<ChangeInfo> applyImpl(BatchUpdate.Factory updateFactory, TopLevelResource parent, ChangeInput input) throws OrmException, IOException, InvalidChangeOperationException, RestApiException, UpdateException, PermissionBackendException {
    if (Strings.isNullOrEmpty(input.project)) {
        throw new BadRequestException("project must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.branch)) {
        throw new BadRequestException("branch must be non-empty");
    }
    if (Strings.isNullOrEmpty(input.subject)) {
        throw new BadRequestException("commit message must be non-empty");
    }
    if (input.status != null) {
        if (input.status != ChangeStatus.NEW && input.status != ChangeStatus.DRAFT) {
            throw new BadRequestException("unsupported change status");
        }
        if (!allowDrafts && input.status == ChangeStatus.DRAFT) {
            throw new MethodNotAllowedException("draft workflow is disabled");
        }
    }
    String refName = RefNames.fullName(input.branch);
    ProjectResource rsrc = projectsCollection.parse(input.project);
    Capable r = rsrc.getControl().canPushToAtLeastOneRef();
    if (r != Capable.OK) {
        throw new AuthException(r.getMessage());
    }
    RefControl refControl = rsrc.getControl().controlForRef(refName);
    if (!refControl.canUpload() || !refControl.isVisible()) {
        throw new AuthException("cannot upload review");
    }
    Project.NameKey project = rsrc.getNameKey();
    try (Repository git = gitManager.openRepository(project);
        ObjectInserter oi = git.newObjectInserter();
        ObjectReader reader = oi.newReader();
        RevWalk rw = new RevWalk(reader)) {
        ObjectId parentCommit;
        List<String> groups;
        if (input.baseChange != null) {
            List<ChangeControl> ctls = changeFinder.find(input.baseChange, rsrc.getControl().getUser());
            if (ctls.size() != 1) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            ChangeControl ctl = Iterables.getOnlyElement(ctls);
            if (!ctl.isVisible(db.get())) {
                throw new UnprocessableEntityException("Base change not found: " + input.baseChange);
            }
            PatchSet ps = psUtil.current(db.get(), ctl.getNotes());
            parentCommit = ObjectId.fromString(ps.getRevision().get());
            groups = ps.getGroups();
        } else {
            Ref destRef = git.getRefDatabase().exactRef(refName);
            if (destRef != null) {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    throw new ResourceConflictException(String.format("Branch %s already exists.", refName));
                }
                parentCommit = destRef.getObjectId();
            } else {
                if (Boolean.TRUE.equals(input.newBranch)) {
                    parentCommit = null;
                } else {
                    throw new UnprocessableEntityException(String.format("Branch %s does not exist.", refName));
                }
            }
            groups = Collections.emptyList();
        }
        RevCommit mergeTip = parentCommit == null ? null : rw.parseCommit(parentCommit);
        Timestamp now = TimeUtil.nowTs();
        IdentifiedUser me = user.get().asIdentifiedUser();
        PersonIdent author = me.newCommitterIdent(now, serverTimeZone);
        AccountState account = accountCache.get(me.getAccountId());
        GeneralPreferencesInfo info = account.getAccount().getGeneralPreferencesInfo();
        ObjectId treeId = mergeTip == null ? emptyTreeId(oi) : mergeTip.getTree();
        ObjectId id = ChangeIdUtil.computeChangeId(treeId, mergeTip, author, author, input.subject);
        String commitMessage = ChangeIdUtil.insertId(input.subject, id);
        if (Boolean.TRUE.equals(info.signedOffBy)) {
            commitMessage += String.format("%s%s", SIGNED_OFF_BY_TAG, account.getAccount().getNameEmail(anonymousCowardName));
        }
        RevCommit c;
        if (input.merge != null) {
            // create a merge commit
            if (!(submitType.equals(SubmitType.MERGE_ALWAYS) || submitType.equals(SubmitType.MERGE_IF_NECESSARY))) {
                throw new BadRequestException("Submit type: " + submitType + " is not supported");
            }
            c = newMergeCommit(git, oi, rw, rsrc.getControl(), mergeTip, input.merge, author, commitMessage);
        } else {
            // create an empty commit
            c = newCommit(oi, rw, author, mergeTip, commitMessage);
        }
        Change.Id changeId = new Change.Id(seq.nextChangeId());
        ChangeInserter ins = changeInserterFactory.create(changeId, c, refName);
        ins.setMessage(String.format("Uploaded patch set %s.", ins.getPatchSetId().get()));
        String topic = input.topic;
        if (topic != null) {
            topic = Strings.emptyToNull(topic.trim());
        }
        ins.setTopic(topic);
        ins.setDraft(input.status == ChangeStatus.DRAFT);
        ins.setPrivate(input.isPrivate != null && input.isPrivate);
        ins.setWorkInProgress(input.workInProgress != null && input.workInProgress);
        ins.setGroups(groups);
        ins.setNotify(input.notify);
        ins.setAccountsToNotify(notifyUtil.resolveAccounts(input.notifyDetails));
        try (BatchUpdate bu = updateFactory.create(db.get(), project, me, now)) {
            bu.setRepository(git, rw, oi);
            bu.insertChange(ins);
            bu.execute();
        }
        ChangeJson json = jsonFactory.noOptions();
        return Response.created(json.format(ins.getChange()));
    } catch (IllegalArgumentException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Timestamp(java.sql.Timestamp) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) Capable(com.google.gerrit.common.data.Capable) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) ChangeControl(com.google.gerrit.server.project.ChangeControl) ObjectReader(org.eclipse.jgit.lib.ObjectReader) RevCommit(org.eclipse.jgit.revwalk.RevCommit) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) ObjectId(org.eclipse.jgit.lib.ObjectId) PatchSet(com.google.gerrit.reviewdb.client.PatchSet) AccountState(com.google.gerrit.server.account.AccountState) Change(com.google.gerrit.reviewdb.client.Change) RevWalk(org.eclipse.jgit.revwalk.RevWalk) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Project(com.google.gerrit.reviewdb.client.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) PersonIdent(org.eclipse.jgit.lib.PersonIdent) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) GeneralPreferencesInfo(com.google.gerrit.extensions.client.GeneralPreferencesInfo) ProjectResource(com.google.gerrit.server.project.ProjectResource) ObjectId(org.eclipse.jgit.lib.ObjectId)

Example 3 with RefControl

use of com.google.gerrit.server.project.RefControl in project gerrit by GerritCodeReview.

the class ProjectAccessFactory method call.

@Override
public ProjectAccess call() throws NoSuchProjectException, IOException, ConfigInvalidException, PermissionBackendException {
    ProjectControl pc = checkProjectControl();
    // Load the current configuration from the repository, ensuring its the most
    // recent version available. If it differs from what was in the project
    // state, force a cache flush now.
    //
    ProjectConfig config;
    try (MetaDataUpdate md = metaDataUpdateFactory.create(projectName)) {
        config = ProjectConfig.read(md);
        if (config.updateGroupNames(groupBackend)) {
            md.setMessage("Update group names\n");
            config.commit(md);
            projectCache.evict(config.getProject());
            pc = checkProjectControl();
        } else if (config.getRevision() != null && !config.getRevision().equals(pc.getProjectState().getConfig().getRevision())) {
            projectCache.evict(config.getProject());
            pc = checkProjectControl();
        }
    }
    final RefControl metaConfigControl = pc.controlForRef(RefNames.REFS_CONFIG);
    List<AccessSection> local = new ArrayList<>();
    Set<String> ownerOf = new HashSet<>();
    Map<AccountGroup.UUID, Boolean> visibleGroups = new HashMap<>();
    for (AccessSection section : config.getAccessSections()) {
        String name = section.getName();
        if (AccessSection.GLOBAL_CAPABILITIES.equals(name)) {
            if (pc.isOwner()) {
                local.add(section);
                ownerOf.add(name);
            } else if (metaConfigControl.isVisible()) {
                local.add(section);
            }
        } else if (RefConfigSection.isValid(name)) {
            RefControl rc = pc.controlForRef(name);
            if (rc.isOwner()) {
                local.add(section);
                ownerOf.add(name);
            } else if (metaConfigControl.isVisible()) {
                local.add(section);
            } else if (rc.isVisible()) {
                // Filter the section to only add rules describing groups that
                // are visible to the current-user. This includes any group the
                // user is a member of, as well as groups they own or that
                // are visible to all users.
                AccessSection dst = null;
                for (Permission srcPerm : section.getPermissions()) {
                    Permission dstPerm = null;
                    for (PermissionRule srcRule : srcPerm.getRules()) {
                        AccountGroup.UUID group = srcRule.getGroup().getUUID();
                        if (group == null) {
                            continue;
                        }
                        Boolean canSeeGroup = visibleGroups.get(group);
                        if (canSeeGroup == null) {
                            try {
                                canSeeGroup = groupControlFactory.controlFor(group).isVisible();
                            } catch (NoSuchGroupException e) {
                                canSeeGroup = Boolean.FALSE;
                            }
                            visibleGroups.put(group, canSeeGroup);
                        }
                        if (canSeeGroup) {
                            if (dstPerm == null) {
                                if (dst == null) {
                                    dst = new AccessSection(name);
                                    local.add(dst);
                                }
                                dstPerm = dst.getPermission(srcPerm.getName(), true);
                            }
                            dstPerm.add(srcRule);
                        }
                    }
                }
            }
        }
    }
    if (ownerOf.isEmpty() && pc.isOwnerAnyRef()) {
        // Special case: If the section list is empty, this project has no current
        // access control information. Rely on what ProjectControl determines
        // is ownership, which probably means falling back to site administrators.
        ownerOf.add(AccessSection.ALL);
    }
    final ProjectAccess detail = new ProjectAccess();
    detail.setProjectName(projectName);
    if (config.getRevision() != null) {
        detail.setRevision(config.getRevision().name());
    }
    detail.setInheritsFrom(config.getProject().getParent(allProjectsName));
    if (projectName.equals(allProjectsName)) {
        if (pc.isOwner()) {
            ownerOf.add(AccessSection.GLOBAL_CAPABILITIES);
        }
    }
    detail.setLocal(local);
    detail.setOwnerOf(ownerOf);
    detail.setCanUpload(metaConfigControl.isVisible() && (pc.isOwner() || metaConfigControl.canUpload()));
    detail.setConfigVisible(pc.isOwner() || metaConfigControl.isVisible());
    detail.setGroupInfo(buildGroupInfo(local));
    detail.setLabelTypes(pc.getLabelTypes());
    detail.setFileHistoryLinks(getConfigFileLogLinks(projectName.get()));
    return detail;
}
Also used : HashMap(java.util.HashMap) PermissionRule(com.google.gerrit.common.data.PermissionRule) RefControl(com.google.gerrit.server.project.RefControl) ArrayList(java.util.ArrayList) ProjectControl(com.google.gerrit.server.project.ProjectControl) AccessSection(com.google.gerrit.common.data.AccessSection) NoSuchGroupException(com.google.gerrit.common.errors.NoSuchGroupException) ProjectAccess(com.google.gerrit.common.data.ProjectAccess) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Permission(com.google.gerrit.common.data.Permission) ProjectPermission(com.google.gerrit.server.permissions.ProjectPermission) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate) HashSet(java.util.HashSet)

Example 4 with RefControl

use of com.google.gerrit.server.project.RefControl in project gerrit by GerritCodeReview.

the class ReviewProjectAccess method updateProjectConfig.

// TODO(dborowitz): Hack MetaDataUpdate so it can be created within a BatchUpdate and we can avoid
// calling setUpdateRef(false).
@SuppressWarnings("deprecation")
@Override
protected Change.Id updateProjectConfig(ProjectControl projectControl, ProjectConfig config, MetaDataUpdate md, boolean parentProjectUpdate) throws IOException, OrmException, PermissionDeniedException {
    RefControl refsMetaConfigControl = projectControl.controlForRef(RefNames.REFS_CONFIG);
    if (!refsMetaConfigControl.isVisible()) {
        throw new PermissionDeniedException(RefNames.REFS_CONFIG + " not visible");
    }
    if (!projectControl.isOwner() && !refsMetaConfigControl.canUpload()) {
        throw new PermissionDeniedException("cannot upload to " + RefNames.REFS_CONFIG);
    }
    md.setInsertChangeId(true);
    Change.Id changeId = new Change.Id(seq.nextChangeId());
    RevCommit commit = config.commitToNewRef(md, new PatchSet.Id(changeId, Change.INITIAL_PATCH_SET_ID).toRefName());
    if (commit.getId().equals(base)) {
        return null;
    }
    try (ObjectInserter objInserter = md.getRepository().newObjectInserter();
        ObjectReader objReader = objInserter.newReader();
        RevWalk rw = new RevWalk(objReader);
        BatchUpdate bu = updateFactory.create(db, config.getProject().getNameKey(), projectControl.getUser(), TimeUtil.nowTs())) {
        bu.setRepository(md.getRepository(), rw, objInserter);
        bu.insertChange(changeInserterFactory.create(changeId, commit, RefNames.REFS_CONFIG).setValidate(false).setUpdateRef(// Created by commitToNewRef.
        false));
        bu.execute();
    } catch (UpdateException | RestApiException e) {
        throw new IOException(e);
    }
    ChangeResource rsrc;
    try {
        rsrc = changes.parse(changeId);
    } catch (ResourceNotFoundException e) {
        throw new IOException(e);
    }
    addProjectOwnersAsReviewers(rsrc);
    if (parentProjectUpdate) {
        addAdministratorsAsReviewers(rsrc);
    }
    return changeId;
}
Also used : RefControl(com.google.gerrit.server.project.RefControl) Change(com.google.gerrit.reviewdb.client.Change) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) BatchUpdate(com.google.gerrit.server.update.BatchUpdate) ChangeResource(com.google.gerrit.server.change.ChangeResource) ObjectInserter(org.eclipse.jgit.lib.ObjectInserter) PermissionDeniedException(com.google.gerrit.common.errors.PermissionDeniedException) ObjectReader(org.eclipse.jgit.lib.ObjectReader) ObjectId(org.eclipse.jgit.lib.ObjectId) UpdateException(com.google.gerrit.server.update.UpdateException) RestApiException(com.google.gerrit.extensions.restapi.RestApiException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) RevCommit(org.eclipse.jgit.revwalk.RevCommit)

Example 5 with RefControl

use of com.google.gerrit.server.project.RefControl 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());
    }
}
Also used : InvalidChangeOperationException(com.google.gerrit.server.project.InvalidChangeOperationException) IntegrationException(com.google.gerrit.server.git.IntegrationException) RefControl(com.google.gerrit.server.project.RefControl) AuthException(com.google.gerrit.extensions.restapi.AuthException) Change(com.google.gerrit.reviewdb.client.Change) ProjectControl(com.google.gerrit.server.project.ProjectControl) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Capable(com.google.gerrit.common.data.Capable) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) ChangeControl(com.google.gerrit.server.project.ChangeControl) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Aggregations

RefControl (com.google.gerrit.server.project.RefControl)8 AuthException (com.google.gerrit.extensions.restapi.AuthException)5 Change (com.google.gerrit.reviewdb.client.Change)5 Capable (com.google.gerrit.common.data.Capable)4 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)4 ProjectControl (com.google.gerrit.server.project.ProjectControl)4 RevCommit (org.eclipse.jgit.revwalk.RevCommit)4 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)3 IOException (java.io.IOException)3 Project (com.google.gerrit.reviewdb.client.Project)2 IntegrationException (com.google.gerrit.server.git.IntegrationException)2 ChangeControl (com.google.gerrit.server.project.ChangeControl)2 InvalidChangeOperationException (com.google.gerrit.server.project.InvalidChangeOperationException)2 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)2 ObjectId (org.eclipse.jgit.lib.ObjectId)2 ObjectInserter (org.eclipse.jgit.lib.ObjectInserter)2 ObjectReader (org.eclipse.jgit.lib.ObjectReader)2 RevWalk (org.eclipse.jgit.revwalk.RevWalk)2 AccessSection (com.google.gerrit.common.data.AccessSection)1 Permission (com.google.gerrit.common.data.Permission)1