Search in sources :

Example 1 with MethodNotAllowedException

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

the class GetAgreements method apply.

@Override
public List<AgreementInfo> apply(AccountResource resource) throws RestApiException {
    if (!agreementsEnabled) {
        throw new MethodNotAllowedException("contributor agreements disabled");
    }
    if (!self.get().isIdentifiedUser()) {
        throw new AuthException("not allowed to get contributor agreements");
    }
    IdentifiedUser user = self.get().asIdentifiedUser();
    if (user != resource.getUser()) {
        throw new AuthException("not allowed to get contributor agreements");
    }
    List<AgreementInfo> results = new ArrayList<>();
    Collection<ContributorAgreement> cas = projectCache.getAllProjects().getConfig().getContributorAgreements();
    for (ContributorAgreement ca : cas) {
        List<AccountGroup.UUID> groupIds = new ArrayList<>();
        for (PermissionRule rule : ca.getAccepted()) {
            if ((rule.getAction() == Action.ALLOW) && (rule.getGroup() != null)) {
                if (rule.getGroup().getUUID() != null) {
                    groupIds.add(rule.getGroup().getUUID());
                } else {
                    log.warn("group \"" + rule.getGroup().getName() + "\" does not " + "exist, referenced in CLA \"" + ca.getName() + "\"");
                }
            }
        }
        if (user.getEffectiveGroups().containsAnyOf(groupIds)) {
            results.add(agreementJson.format(ca));
        }
    }
    return results;
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionRule(com.google.gerrit.common.data.PermissionRule) AgreementInfo(com.google.gerrit.extensions.common.AgreementInfo) ContributorAgreement(com.google.gerrit.common.data.ContributorAgreement) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser)

Example 2 with MethodNotAllowedException

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

the class CreateTag method apply.

@Override
public TagInfo apply(ProjectResource resource, TagInput input) throws RestApiException, IOException, PermissionBackendException {
    if (input == null) {
        input = new TagInput();
    }
    if (input.ref != null && !ref.equals(input.ref)) {
        throw new BadRequestException("ref must match URL");
    }
    if (input.revision == null) {
        input.revision = Constants.HEAD;
    }
    ref = RefUtil.normalizeTagRef(ref);
    RefControl refControl = resource.getControl().controlForRef(ref);
    PermissionBackend.ForRef perm = permissionBackend.user(identifiedUser).project(resource.getNameKey()).ref(ref);
    try (Repository repo = repoManager.openRepository(resource.getNameKey())) {
        ObjectId revid = RefUtil.parseBaseRevision(repo, resource.getNameKey(), input.revision);
        RevWalk rw = RefUtil.verifyConnected(repo, revid);
        RevObject object = rw.parseAny(revid);
        rw.reset();
        boolean isAnnotated = Strings.emptyToNull(input.message) != null;
        boolean isSigned = isAnnotated && input.message.contains("-----BEGIN PGP SIGNATURE-----\n");
        if (isSigned) {
            throw new MethodNotAllowedException("Cannot create signed tag \"" + ref + "\"");
        } else if (isAnnotated && !refControl.canPerform(Permission.CREATE_TAG)) {
            throw new AuthException("Cannot create annotated tag \"" + ref + "\"");
        } else {
            perm.check(RefPermission.CREATE);
        }
        if (repo.getRefDatabase().exactRef(ref) != null) {
            throw new ResourceConflictException("tag \"" + ref + "\" already exists");
        }
        try (Git git = new Git(repo)) {
            TagCommand tag = git.tag().setObjectId(object).setName(ref.substring(R_TAGS.length())).setAnnotated(isAnnotated).setSigned(isSigned);
            if (isAnnotated) {
                tag.setMessage(input.message).setTagger(identifiedUser.get().newCommitterIdent(TimeUtil.nowTs(), TimeZone.getDefault()));
            }
            Ref result = tag.call();
            tagCache.updateFastForward(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId());
            referenceUpdated.fire(resource.getNameKey(), ref, ObjectId.zeroId(), result.getObjectId(), identifiedUser.get().getAccount());
            try (RevWalk w = new RevWalk(repo)) {
                return ListTags.createTagInfo(perm, result, w);
            }
        }
    } catch (InvalidRevisionException e) {
        throw new BadRequestException("Invalid base revision");
    } catch (GitAPIException e) {
        log.error("Cannot create tag \"" + ref + "\"", e);
        throw new IOException(e);
    }
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) ObjectId(org.eclipse.jgit.lib.ObjectId) RevObject(org.eclipse.jgit.revwalk.RevObject) AuthException(com.google.gerrit.extensions.restapi.AuthException) TagInput(com.google.gerrit.extensions.api.projects.TagInput) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) TagCommand(org.eclipse.jgit.api.TagCommand) GitAPIException(org.eclipse.jgit.api.errors.GitAPIException) Repository(org.eclipse.jgit.lib.Repository) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) Ref(org.eclipse.jgit.lib.Ref) Git(org.eclipse.jgit.api.Git) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) InvalidRevisionException(com.google.gerrit.server.project.RefUtil.InvalidRevisionException)

Example 3 with MethodNotAllowedException

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

the class InstallPlugin method apply.

@Override
public Response<PluginInfo> apply(TopLevelResource resource, Input input) throws BadRequestException, MethodNotAllowedException, IOException {
    if (!loader.isRemoteAdminEnabled()) {
        throw new MethodNotAllowedException("remote installation is disabled");
    }
    try {
        try (InputStream in = openStream(input)) {
            String pluginName = loader.installPluginFromStream(name, in);
            ListPlugins.PluginInfo info = new ListPlugins.PluginInfo(loader.get(pluginName));
            return created ? Response.created(info) : Response.ok(info);
        }
    } catch (PluginInstallException e) {
        StringWriter buf = new StringWriter();
        buf.write(String.format("cannot install %s", name));
        if (e.getCause() instanceof ZipException) {
            buf.write(": ");
            buf.write(e.getCause().getMessage());
        } else {
            buf.write(":\n");
            PrintWriter pw = new PrintWriter(buf);
            e.printStackTrace(pw);
            pw.flush();
        }
        throw new BadRequestException(buf.toString());
    }
}
Also used : PluginInfo(com.google.gerrit.server.plugins.ListPlugins.PluginInfo) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) StringWriter(java.io.StringWriter) InputStream(java.io.InputStream) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) PluginInfo(com.google.gerrit.server.plugins.ListPlugins.PluginInfo) ZipException(java.util.zip.ZipException) PrintWriter(java.io.PrintWriter)

Example 4 with MethodNotAllowedException

use of com.google.gerrit.extensions.restapi.MethodNotAllowedException 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 5 with MethodNotAllowedException

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

the class CreateEmail method apply.

public Response<EmailInfo> apply(IdentifiedUser user, EmailInput input) throws AuthException, BadRequestException, ResourceConflictException, ResourceNotFoundException, OrmException, EmailException, MethodNotAllowedException, IOException, ConfigInvalidException, PermissionBackendException {
    if (input.email != null && !email.equals(input.email)) {
        throw new BadRequestException("email address must match URL");
    }
    EmailInfo info = new EmailInfo();
    info.email = email;
    if (input.noConfirmation || isDevMode) {
        if (isDevMode) {
            log.warn("skipping email validation in developer mode");
        }
        try {
            accountManager.link(user.getAccountId(), AuthRequest.forEmail(email));
        } catch (AccountException e) {
            throw new ResourceConflictException(e.getMessage());
        }
        if (input.preferred) {
            putPreferred.apply(new AccountResource.Email(user, email), null);
            info.preferred = true;
        }
    } else {
        try {
            RegisterNewEmailSender sender = registerNewEmailFactory.create(email);
            if (!sender.isAllowed()) {
                throw new MethodNotAllowedException("Not allowed to add email address " + email);
            }
            sender.send();
            info.pendingConfirmation = true;
        } catch (EmailException | RuntimeException e) {
            log.error("Cannot send email verification message to " + email, e);
            throw e;
        }
    }
    return Response.created(info);
}
Also used : ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) RegisterNewEmailSender(com.google.gerrit.server.mail.send.RegisterNewEmailSender) EmailException(com.google.gerrit.common.errors.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) EmailInfo(com.google.gerrit.extensions.common.EmailInfo)

Aggregations

MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)66 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)27 AuthException (com.google.gerrit.extensions.restapi.AuthException)23 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)16 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)16 Test (org.junit.Test)16 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)15 AccountGroup (com.google.gerrit.reviewdb.client.AccountGroup)11 IOException (java.io.IOException)11 ArrayList (java.util.ArrayList)11 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)10 Account (com.google.gerrit.reviewdb.client.Account)9 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)8 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)7 BatchUpdate (com.google.gerrit.server.update.BatchUpdate)7 Account (com.google.gerrit.entities.Account)6 GroupInfo (com.google.gerrit.extensions.common.GroupInfo)5 Response (com.google.gerrit.extensions.restapi.Response)5 Change (com.google.gerrit.reviewdb.client.Change)5 CurrentUser (com.google.gerrit.server.CurrentUser)5