Search in sources :

Example 16 with AuthException

use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.

the class DeleteRef method createDeleteCommand.

private ReceiveCommand createDeleteCommand(ProjectResource project, Repository r, String refName) throws OrmException, IOException, ResourceConflictException, PermissionBackendException {
    Ref ref = r.getRefDatabase().getRef(refName);
    ReceiveCommand command;
    if (ref == null) {
        command = new ReceiveCommand(ObjectId.zeroId(), ObjectId.zeroId(), refName);
        command.setResult(Result.REJECTED_OTHER_REASON, "it doesn't exist or you do not have permission to delete it");
        return command;
    }
    command = new ReceiveCommand(ref.getObjectId(), ObjectId.zeroId(), ref.getName());
    try {
        permissionBackend.user(identifiedUser).project(project.getNameKey()).ref(refName).check(RefPermission.DELETE);
    } catch (AuthException denied) {
        command.setResult(Result.REJECTED_OTHER_REASON, "it doesn't exist or you do not have permission to delete it");
    }
    if (!refName.startsWith(R_TAGS)) {
        Branch.NameKey branchKey = new Branch.NameKey(project.getNameKey(), ref.getName());
        if (!queryProvider.get().setLimit(1).byBranchOpen(branchKey).isEmpty()) {
            command.setResult(Result.REJECTED_OTHER_REASON, "it has open changes");
        }
    }
    RefUpdate u = r.updateRef(refName);
    u.setForceUpdate(true);
    u.setExpectedOldObjectId(r.exactRef(refName).getObjectId());
    u.setNewObjectId(ObjectId.zeroId());
    refDeletionValidator.validateRefOperation(project.getName(), identifiedUser.get(), u);
    return command;
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) Ref(org.eclipse.jgit.lib.Ref) Branch(com.google.gerrit.reviewdb.client.Branch) AuthException(com.google.gerrit.extensions.restapi.AuthException) RefUpdate(org.eclipse.jgit.lib.RefUpdate) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate)

Example 17 with AuthException

use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.

the class CreateBranch method apply.

@Override
public BranchInfo apply(ProjectResource rsrc, BranchInput input) throws BadRequestException, AuthException, ResourceConflictException, IOException {
    if (input == null) {
        input = new BranchInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    while (ref.startsWith("/")) {
        ref = ref.substring(1);
    }
    ref = RefNames.fullName(ref);
    if (!Repository.isValidRefName(ref)) {
        throw new BadRequestException("invalid branch name \"" + ref + "\"");
    }
    if (MagicBranch.isMagicBranch(ref)) {
        throw new BadRequestException("not allowed to create branches under \"" + MagicBranch.getMagicRefNamePrefix(ref) + "\"");
    }
    final Branch.NameKey name = new Branch.NameKey(rsrc.getNameKey(), ref);
    final RefControl refControl = rsrc.getControl().controlForRef(name);
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, rsrc.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        if (ref.startsWith(Constants.R_HEADS)) {
            //
            try {
                object = rw.parseCommit(object);
            } catch (IncorrectObjectTypeException notCommit) {
                throw new BadRequestException("\"" + input.revision + "\" not a commit");
            }
        }
        if (!refControl.canCreate(db.get(), repo, object)) {
            throw new AuthException("Cannot create \"" + ref + "\"");
        }
        try {
            final RefUpdate u = repo.updateRef(ref);
            u.setExpectedOldObjectId(ObjectId.zeroId());
            u.setNewObjectId(object.copy());
            u.setRefLogIdent(identifiedUser.get().newRefLogIdent());
            u.setRefLogMessage("created via REST from " + input.revision, false);
            refCreationValidator.validateRefOperation(rsrc.getName(), identifiedUser.get(), u);
            final RefUpdate.Result result = u.update(rw);
            switch(result) {
                case FAST_FORWARD:
                case NEW:
                case NO_CHANGE:
                    referenceUpdated.fire(name.getParentKey(), u, ReceiveCommand.Type.CREATE, identifiedUser.get().getAccount());
                    break;
                case LOCK_FAILURE:
                    if (repo.getRefDatabase().exactRef(ref) != null) {
                        throw new ResourceConflictException("branch \"" + ref + "\" already exists");
                    }
                    String refPrefix = RefUtil.getRefPrefix(ref);
                    while (!Constants.R_HEADS.equals(refPrefix)) {
                        if (repo.getRefDatabase().exactRef(refPrefix) != null) {
                            throw new ResourceConflictException("Cannot create branch \"" + ref + "\" since it conflicts with branch \"" + refPrefix + "\".");
                        }
                        refPrefix = RefUtil.getRefPrefix(refPrefix);
                    }
                //$FALL-THROUGH$
                case FORCED:
                case IO_FAILURE:
                case NOT_ATTEMPTED:
                case REJECTED:
                case REJECTED_CURRENT_BRANCH:
                case RENAMED:
                default:
                    {
                        throw new IOException(result.name());
                    }
            }
            BranchInfo info = new BranchInfo();
            info.ref = ref;
            info.revision = revid.getName();
            info.canDelete = permissionBackend.user(identifiedUser).ref(name).testOrFalse(RefPermission.DELETE) ? true : null;
            return info;
        } catch (IOException err) {
            log.error("Cannot create branch \"" + name + "\"", err);
            throw err;
        }
    } catch (RefUtil.InvalidRevisionException e) {
        throw new BadRequestException("invalid revision \"" + input.revision + "\"");
    }
}
Also used : BranchInfo(com.google.gerrit.extensions.api.projects.BranchInfo) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) IncorrectObjectTypeException(org.eclipse.jgit.errors.IncorrectObjectTypeException) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MagicBranch(com.google.gerrit.server.util.MagicBranch) Branch(com.google.gerrit.reviewdb.client.Branch) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) BranchInput(com.google.gerrit.extensions.api.projects.BranchInput) RefUpdate(org.eclipse.jgit.lib.RefUpdate)

Example 18 with AuthException

use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.

the class GetReflog method apply.

@Override
public List<ReflogEntryInfo> apply(BranchResource rsrc) throws AuthException, ResourceNotFoundException, RepositoryNotFoundException, IOException {
    if (!rsrc.getControl().isOwner()) {
        throw new AuthException("not project owner");
    }
    try (Repository repo = repoManager.openRepository(rsrc.getNameKey())) {
        ReflogReader r = repo.getReflogReader(rsrc.getRef());
        if (r == null) {
            throw new ResourceNotFoundException(rsrc.getRef());
        }
        List<ReflogEntry> entries;
        if (from == null && to == null) {
            entries = limit > 0 ? r.getReverseEntries(limit) : r.getReverseEntries();
        } else {
            entries = limit > 0 ? new ArrayList<>(limit) : new ArrayList<>();
            for (ReflogEntry e : r.getReverseEntries()) {
                Timestamp timestamp = new Timestamp(e.getWho().getWhen().getTime());
                if ((from == null || from.before(timestamp)) && (to == null || to.after(timestamp))) {
                    entries.add(e);
                }
                if (limit > 0 && entries.size() >= limit) {
                    break;
                }
            }
        }
        return Lists.transform(entries, ReflogEntryInfo::new);
    }
}
Also used : Repository(org.eclipse.jgit.lib.Repository) ReflogReader(org.eclipse.jgit.lib.ReflogReader) ReflogEntry(org.eclipse.jgit.lib.ReflogEntry) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Timestamp(java.sql.Timestamp)

Example 19 with AuthException

use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.

the class PutDescription method apply.

@Override
public Response<String> apply(ProjectResource resource, DescriptionInput input) throws AuthException, ResourceConflictException, ResourceNotFoundException, IOException {
    if (input == null) {
        // Delete would set description to null.
        input = new DescriptionInput();
    }
    ProjectControl ctl = resource.getControl();
    IdentifiedUser user = ctl.getUser().asIdentifiedUser();
    if (!ctl.isOwner()) {
        throw new AuthException("not project owner");
    }
    try (MetaDataUpdate md = updateFactory.create(resource.getNameKey())) {
        ProjectConfig config = ProjectConfig.read(md);
        Project project = config.getProject();
        project.setDescription(Strings.emptyToNull(input.description));
        String msg = MoreObjects.firstNonNull(Strings.emptyToNull(input.commitMessage), "Updated description.\n");
        if (!msg.endsWith("\n")) {
            msg += "\n";
        }
        md.setAuthor(user);
        md.setMessage(msg);
        config.commit(md);
        cache.evict(ctl.getProject());
        md.getRepository().setGitwebDescription(project.getDescription());
        return Strings.isNullOrEmpty(project.getDescription()) ? Response.<String>none() : Response.ok(project.getDescription());
    } catch (RepositoryNotFoundException notFound) {
        throw new ResourceNotFoundException(resource.getName());
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(String.format("invalid project.config: %s", e.getMessage()));
    }
}
Also used : ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Project(com.google.gerrit.reviewdb.client.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) DescriptionInput(com.google.gerrit.extensions.api.projects.DescriptionInput) AuthException(com.google.gerrit.extensions.restapi.AuthException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 20 with AuthException

use of com.google.gerrit.extensions.restapi.AuthException in project gerrit by GerritCodeReview.

the class MergeOp method merge.

/**
   * Merges the given change.
   *
   * <p>Depending on the server configuration, more changes may be affected, e.g. by submission of a
   * topic or via superproject subscriptions. All affected changes are integrated using the projects
   * integration strategy.
   *
   * @param db the review database.
   * @param change the change to be merged.
   * @param caller the identity of the caller
   * @param checkSubmitRules whether the prolog submit rules should be evaluated
   * @param submitInput parameters regarding the merge
   * @throws OrmException an error occurred reading or writing the database.
   * @throws RestApiException if an error occurred.
   */
public void merge(ReviewDb db, Change change, IdentifiedUser caller, boolean checkSubmitRules, SubmitInput submitInput, boolean dryrun) throws OrmException, RestApiException {
    this.submitInput = submitInput;
    this.accountsToNotify = notifyUtil.resolveAccounts(submitInput.notifyDetails);
    this.dryrun = dryrun;
    this.caller = caller;
    this.ts = TimeUtil.nowTs();
    submissionId = RequestId.forChange(change);
    this.db = db;
    orm.setContext(db, ts, caller, submissionId);
    logDebug("Beginning integration of {}", change);
    try {
        ChangeSet cs = mergeSuperSet.setMergeOpRepoManager(orm).completeChangeSet(db, change, caller);
        checkState(cs.ids().contains(change.getId()), "change %s missing from %s", change.getId(), cs);
        if (cs.furtherHiddenChanges()) {
            throw new AuthException("A change to be submitted with " + change.getId() + " is not visible");
        }
        this.commitStatus = new CommitStatus(cs);
        MergeSuperSet.reloadChanges(cs);
        logDebug("Calculated to merge {}", cs);
        if (checkSubmitRules) {
            logDebug("Checking submit rules and state");
            checkSubmitRulesAndState(cs);
        } else {
            logDebug("Bypassing submit rules");
            bypassSubmitRules(cs);
        }
        try {
            integrateIntoHistory(cs);
        } catch (IntegrationException e) {
            logError("Error from integrateIntoHistory", e);
            throw new ResourceConflictException(e.getMessage(), e);
        }
    } catch (IOException e) {
        // Anything before the merge attempt is an error
        throw new OrmException(e);
    }
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) OrmException(com.google.gwtorm.server.OrmException) AuthException(com.google.gerrit.extensions.restapi.AuthException) IOException(java.io.IOException)

Aggregations

AuthException (com.google.gerrit.extensions.restapi.AuthException)68 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)22 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)20 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)15 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)14 Change (com.google.gerrit.reviewdb.client.Change)13 IOException (java.io.IOException)12 Account (com.google.gerrit.reviewdb.client.Account)11 Project (com.google.gerrit.reviewdb.client.Project)11 CurrentUser (com.google.gerrit.server.CurrentUser)11 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)11 PermissionBackendException (com.google.gerrit.server.permissions.PermissionBackendException)11 ArrayList (java.util.ArrayList)11 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)10 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)8 ChangeControl (com.google.gerrit.server.project.ChangeControl)7 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)6 OrmException (com.google.gwtorm.server.OrmException)6 RepositoryNotFoundException (org.eclipse.jgit.errors.RepositoryNotFoundException)6