Search in sources :

Example 41 with UnprocessableEntityException

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

the class PutAgreement method apply.

@Override
public Response<String> apply(AccountResource resource, AgreementInput input) throws IOException, OrmException, RestApiException {
    if (!agreementsEnabled) {
        throw new MethodNotAllowedException("contributor agreements disabled");
    }
    if (self.get() != resource.getUser()) {
        throw new AuthException("not allowed to enter contributor agreement");
    }
    String agreementName = Strings.nullToEmpty(input.name);
    ContributorAgreement ca = projectCache.getAllProjects().getConfig().getContributorAgreement(agreementName);
    if (ca == null) {
        throw new UnprocessableEntityException("contributor agreement not found");
    }
    if (ca.getAutoVerify() == null) {
        throw new BadRequestException("cannot enter a non-autoVerify agreement");
    }
    AccountGroup.UUID uuid = ca.getAutoVerify().getUUID();
    if (uuid == null) {
        throw new ResourceConflictException("autoverify group uuid not found");
    }
    AccountGroup group = groupCache.get(uuid);
    if (group == null) {
        throw new ResourceConflictException("autoverify group not found");
    }
    Account account = self.get().getAccount();
    addMembers.addMembers(group.getId(), ImmutableList.of(account.getId()));
    agreementSignup.fire(account, agreementName);
    return Response.ok(agreementName);
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Account(com.google.gerrit.reviewdb.client.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) ContributorAgreement(com.google.gerrit.common.data.ContributorAgreement) AuthException(com.google.gerrit.extensions.restapi.AuthException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException)

Example 42 with UnprocessableEntityException

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

the class CreateAccount method apply.

@Override
public Response<AccountInfo> apply(TopLevelResource rsrc, AccountInput input) throws BadRequestException, ResourceConflictException, UnprocessableEntityException, OrmException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new AccountInput();
    }
    if (input.username != null && !username.equals(input.username)) {
        throw new BadRequestException("username must match URL");
    }
    if (!username.matches(Account.USER_NAME_PATTERN)) {
        throw new BadRequestException("Username '" + username + "' must contain only letters, numbers, _, - or .");
    }
    Set<AccountGroup.Id> groups = parseGroups(input.groups);
    Account.Id id = new Account.Id(db.nextAccountId());
    ExternalId extUser = ExternalId.createUsername(username, id, input.httpPassword);
    if (externalIds.get(extUser.key()) != null) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        if (externalIds.get(ExternalId.Key.create(SCHEME_MAILTO, input.email)) != null) {
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
        if (!validator.isValid(input.email)) {
            throw new BadRequestException("invalid email address");
        }
    }
    List<ExternalId> extIds = new ArrayList<>();
    extIds.add(extUser);
    for (AccountExternalIdCreator c : externalIdCreators) {
        extIds.addAll(c.create(id, username, input.email));
    }
    ExternalIdsUpdate externalIdsUpdate = externalIdsUpdateFactory.create();
    try {
        externalIdsUpdate.insert(extIds);
    } catch (OrmDuplicateKeyException duplicateKey) {
        throw new ResourceConflictException("username '" + username + "' already exists");
    }
    if (input.email != null) {
        try {
            externalIdsUpdate.insert(ExternalId.createEmail(id, input.email));
        } catch (OrmDuplicateKeyException duplicateKey) {
            try {
                externalIdsUpdate.delete(extUser);
            } catch (IOException | ConfigInvalidException cleanupError) {
            // Ignored
            }
            throw new UnprocessableEntityException("email '" + input.email + "' already exists");
        }
    }
    Account a = new Account(id, TimeUtil.nowTs());
    a.setFullName(input.name);
    a.setPreferredEmail(input.email);
    accountsUpdate.create().insert(db, a);
    for (AccountGroup.Id groupId : groups) {
        AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, groupId));
        auditService.dispatchAddAccountsToGroup(currentUser.get().getAccountId(), Collections.singleton(m));
        db.accountGroupMembers().insert(Collections.singleton(m));
    }
    if (input.sshKey != null) {
        try {
            authorizedKeys.addKey(id, input.sshKey);
            sshKeyCache.evict(username);
        } catch (InvalidSshKeyException e) {
            throw new BadRequestException(e.getMessage());
        }
    }
    accountCache.evictByUsername(username);
    byEmailCache.evict(input.email);
    indexer.index(id);
    AccountLoader loader = infoLoader.create(true);
    AccountInfo info = loader.get(id);
    loader.fill();
    return Response.created(info);
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) OrmDuplicateKeyException(com.google.gwtorm.server.OrmDuplicateKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ExternalIdsUpdate(com.google.gerrit.server.account.externalids.ExternalIdsUpdate) ArrayList(java.util.ArrayList) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) AccountExternalIdCreator(com.google.gerrit.server.api.accounts.AccountExternalIdCreator) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AccountInput(com.google.gerrit.extensions.api.accounts.AccountInput) AccountInfo(com.google.gerrit.extensions.common.AccountInfo)

Example 43 with UnprocessableEntityException

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

the class SetParent method validateParentUpdate.

public void validateParentUpdate(final ProjectControl ctl, String newParent, boolean checkIfAdmin) throws AuthException, ResourceConflictException, UnprocessableEntityException, PermissionBackendException {
    IdentifiedUser user = ctl.getUser().asIdentifiedUser();
    if (checkIfAdmin) {
        permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
    }
    if (ctl.getProject().getNameKey().equals(allProjects)) {
        throw new ResourceConflictException("cannot set parent of " + allProjects.get());
    }
    newParent = Strings.emptyToNull(newParent);
    if (newParent != null) {
        ProjectState parent = cache.get(new Project.NameKey(newParent));
        if (parent == null) {
            throw new UnprocessableEntityException("parent project " + newParent + " not found");
        }
        if (Iterables.tryFind(parent.tree(), p -> {
            return p.getProject().getNameKey().equals(ctl.getProject().getNameKey());
        }).isPresent()) {
            throw new ResourceConflictException("cycle exists between " + ctl.getProject().getName() + " and " + parent.getProject().getName());
        }
    }
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) Project(com.google.gerrit.reviewdb.client.Project) Iterables(com.google.common.collect.Iterables) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate) Inject(com.google.inject.Inject) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) MoreObjects(com.google.common.base.MoreObjects) IOException(java.io.IOException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) DefaultInput(com.google.gerrit.extensions.restapi.DefaultInput) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) Strings(com.google.common.base.Strings) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AuthException(com.google.gerrit.extensions.restapi.AuthException) ProjectConfig(com.google.gerrit.server.git.ProjectConfig) Input(com.google.gerrit.server.project.SetParent.Input) Singleton(com.google.inject.Singleton) Project(com.google.gerrit.reviewdb.client.Project) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser)

Example 44 with UnprocessableEntityException

use of com.google.gerrit.extensions.restapi.UnprocessableEntityException 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) {
            logger.atWarning().withCause(e).log("cannot check runAs");
            replyError(req, res, SC_INTERNAL_SERVER_ERROR, RUN_AS + " unavailable", null);
            return;
        }
        Account.Id target;
        try {
            target = accountResolver.resolve(runas).asUnique().account().id();
        } catch (UnprocessableEntityException e) {
            replyError(req, res, SC_FORBIDDEN, "no account matches " + RUN_AS, null);
            return;
        } catch (IOException | ConfigInvalidException | RuntimeException e) {
            logger.atWarning().withCause(e).log("cannot resolve account for %s", RUN_AS);
            replyError(req, res, SC_INTERNAL_SERVER_ERROR, "cannot resolve " + RUN_AS, e);
            return;
        }
        session.get().setUserAccountId(target);
    }
    chain.doFilter(req, res);
}
Also used : Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) CurrentUser(com.google.gerrit.server.CurrentUser) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthException(com.google.gerrit.extensions.restapi.AuthException) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IOException(java.io.IOException) HttpServletRequest(javax.servlet.http.HttpServletRequest)

Example 45 with UnprocessableEntityException

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

the class ReviewerModifier method byAccountId.

@Nullable
private ReviewerModification byAccountId(ReviewerInput input, ChangeNotes notes, CurrentUser user) throws PermissionBackendException, IOException, ConfigInvalidException {
    IdentifiedUser reviewerUser;
    boolean exactMatchFound = false;
    try {
        reviewerUser = accountResolver.resolveIncludeInactive(input.reviewer).asUniqueUser();
        if (input.reviewer.equalsIgnoreCase(reviewerUser.getName()) || input.reviewer.equals(String.valueOf(reviewerUser.getAccountId()))) {
            exactMatchFound = true;
        }
    } catch (UnprocessableEntityException e) {
        // group, but if not, the error message will be useful.
        return fail(input, FailureType.NOT_FOUND, e.getMessage());
    }
    if (isValidReviewer(notes.getChange().getDest(), reviewerUser.getAccount())) {
        return new ReviewerModification(input, notes, user, ImmutableSet.of(reviewerUser.getAccount()), null, exactMatchFound, false);
    }
    return fail(input, FailureType.OTHER, MessageFormat.format(ChangeMessages.get().reviewerCantSeeChange, input.reviewer));
}
Also used : UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) Nullable(com.google.gerrit.common.Nullable)

Aggregations

UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)78 AuthException (com.google.gerrit.extensions.restapi.AuthException)31 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)27 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)25 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)23 Test (org.junit.Test)23 IOException (java.io.IOException)13 ArrayList (java.util.ArrayList)13 Account (com.google.gerrit.entities.Account)12 Ref (org.eclipse.jgit.lib.Ref)10 PushOneCommit (com.google.gerrit.acceptance.PushOneCommit)9 CurrentUser (com.google.gerrit.server.CurrentUser)9 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)9 PermissionBackend (com.google.gerrit.server.permissions.PermissionBackend)9 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)9 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)8 Map (java.util.Map)8 ObjectId (org.eclipse.jgit.lib.ObjectId)8 RevCommit (org.eclipse.jgit.revwalk.RevCommit)8 Nullable (com.google.gerrit.common.Nullable)7