Search in sources :

Example 36 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class CommitRewriter method verifyCommit.

/**
 * Verifies that the commit does not contain user data of accounts in {@code accounts}.
 */
private boolean verifyCommit(String commitMessage, PersonIdent author, Collection<AccountState> accounts) {
    for (AccountState accountState : accounts) {
        Account account = accountState.account();
        if (commitMessage.contains(account.getName())) {
            return false;
        }
        if (account.fullName() != null && commitMessage.contains(account.fullName())) {
            return false;
        }
        if (account.displayName() != null && commitMessage.contains(account.displayName())) {
            return false;
        }
        if (account.preferredEmail() != null && commitMessage.contains(account.preferredEmail())) {
            return false;
        }
        if (accountState.userName().isPresent() && commitMessage.contains(accountState.userName().get())) {
            return false;
        }
        Stream<String> allEmails = accountState.externalIds().stream().map(ExternalId::email).filter(Objects::nonNull);
        if (allEmails.anyMatch(email -> commitMessage.contains(email))) {
            return false;
        }
        if (author.toString().contains(account.getName())) {
            return false;
        }
    }
    return true;
}
Also used : Account(com.google.gerrit.entities.Account) Objects(java.util.Objects) AccountState(com.google.gerrit.server.account.AccountState)

Example 37 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class CommitRewriter method backfillProject.

/**
 * Rewrites commit history of {@link RefNames#changeMetaRef}s in single {@code repo}. Only
 * rewrites branch if necessary, i.e. if there were any commits that contained user data.
 *
 * <p>See {@link RunOptions} for the execution and output options.
 *
 * @param project project to backfill
 * @param repo repo to backfill
 * @param options {@link RunOptions} to control how the run is executed.
 * @return BackfillResult
 */
public BackfillResult backfillProject(Project.NameKey project, Repository repo, RunOptions options) {
    checkState(options.maxRefsInBatch > 0 && options.maxRefsToUpdate > 0, "Expected maxRefsInBatch>0 && <= maxRefsToUpdate>0");
    checkState(options.maxRefsInBatch <= options.maxRefsToUpdate, "Expected maxRefsInBatch(%s) <= maxRefsToUpdate(%s)", options.maxRefsInBatch, options.maxRefsToUpdate);
    BackfillResult result = new BackfillResult();
    result.ok = true;
    int refsInUpdate = 0;
    @SuppressWarnings("resource") RefsUpdate refsUpdate = null;
    try {
        for (Ref ref : repo.getRefDatabase().getRefsByPrefix(RefNames.REFS_CHANGES)) {
            if (result.fixedRefDiff.size() >= options.maxRefsToUpdate) {
                return result;
            }
            Change.Id changeId = Change.Id.fromRef(ref.getName());
            if (changeId == null || !ref.getName().equals(RefNames.changeMetaRef(changeId))) {
                continue;
            }
            try {
                ImmutableSet<AccountState> accountsInChange = ImmutableSet.of();
                if (options.verifyCommits) {
                    try {
                        ChangeNotes changeNotes = changeNotesFactory.create(project, changeId);
                        accountsInChange = collectAccounts(changeNotes);
                    } catch (Exception e) {
                        logger.atWarning().withCause(e).log("Failed to run verification on ref %s", ref);
                    }
                }
                if (refsUpdate == null) {
                    refsUpdate = RefsUpdate.create(repo);
                }
                ChangeFixProgress changeFixProgress = backfillChange(refsUpdate, ref, accountsInChange, options);
                if (changeFixProgress.anyFixesApplied) {
                    refsInUpdate++;
                    refsUpdate.batchRefUpdate().addCommand(new ReceiveCommand(ref.getObjectId(), changeFixProgress.newTipId, ref.getName()));
                    result.fixedRefDiff.put(ref.getName(), changeFixProgress.commitDiffs);
                }
                if (refsInUpdate >= options.maxRefsInBatch || result.fixedRefDiff.size() >= options.maxRefsToUpdate) {
                    processUpdate(options, refsUpdate);
                    refsUpdate = null;
                    refsInUpdate = 0;
                }
                if (!changeFixProgress.isValidAfterFix) {
                    result.refsStillInvalidAfterFix.add(ref.getName());
                }
            } catch (Exception e) {
                logger.atWarning().withCause(e).log("Failed to fix ref %s", ref);
                result.refsFailedToFix.add(ref.getName());
            }
        }
        processUpdate(options, refsUpdate);
    } catch (IOException e) {
        logger.atWarning().log("Failed to fix project %s. Reason: %s", project.get(), e.getMessage());
        result.ok = false;
    } finally {
        if (refsUpdate != null) {
            refsUpdate.close();
        }
    }
    return result;
}
Also used : ReceiveCommand(org.eclipse.jgit.transport.ReceiveCommand) Change(com.google.gerrit.entities.Change) AccountState(com.google.gerrit.server.account.AccountState) IOException(java.io.IOException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) Ref(org.eclipse.jgit.lib.Ref)

Example 38 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class ReviewersUtil method suggestAccounts.

private List<Account.Id> suggestAccounts(SuggestReviewers suggestReviewers) throws BadRequestException {
    try (Timer0.Context ctx = metrics.queryAccountsLatency.start()) {
        // For performance reasons we don't use AccountQueryProvider as it would always load the
        // complete account from the cache (or worse, from NoteDb) even though we only need the ID
        // which we can directly get from the returned results.
        Predicate<AccountState> pred = Predicate.and(AccountPredicates.isActive(), accountQueryBuilder.defaultQuery(suggestReviewers.getQuery()));
        logger.atFine().log("accounts index query: %s", pred);
        accountIndexRewriter.validateMaxTermsInQuery(pred);
        boolean useLegacyNumericFields = accountIndexes.getSearchIndex().getSchema().useLegacyNumericFields();
        FieldDef<AccountState, ?> idField = useLegacyNumericFields ? AccountField.ID : AccountField.ID_STR;
        ResultSet<FieldBundle> result = accountIndexes.getSearchIndex().getSource(pred, QueryOptions.create(indexConfig, 0, suggestReviewers.getLimit(), ImmutableSet.of(idField.getName()))).readRaw();
        List<Account.Id> matches = result.toList().stream().map(f -> fromIdField(f, useLegacyNumericFields)).collect(toList());
        logger.atFine().log("Matches: %s", matches);
        return matches;
    } catch (TooManyTermsInQueryException e) {
        throw new BadRequestException(e.getMessage());
    } catch (QueryParseException e) {
        logger.atWarning().withCause(e).log("Suggesting accounts failed, return empty result.");
        return ImmutableList.of();
    } catch (StorageException e) {
        if (e.getCause() instanceof TooManyTermsInQueryException) {
            throw new BadRequestException(e.getMessage());
        }
        if (e.getCause() instanceof QueryParseException) {
            return ImmutableList.of();
        }
        throw e;
    }
}
Also used : GroupBackend(com.google.gerrit.server.account.GroupBackend) Inject(com.google.inject.Inject) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ReviewerModifier(com.google.gerrit.server.change.ReviewerModifier) EnumSet(java.util.EnumSet) FieldDef(com.google.gerrit.index.FieldDef) ImmutableSet(com.google.common.collect.ImmutableSet) GroupBaseInfo(com.google.gerrit.extensions.common.GroupBaseInfo) Timer0(com.google.gerrit.metrics.Timer0) Account(com.google.gerrit.entities.Account) FillOptions(com.google.gerrit.server.account.AccountDirectory.FillOptions) AccountQueryBuilder(com.google.gerrit.server.query.account.AccountQueryBuilder) Set(java.util.Set) AccountIndexCollection(com.google.gerrit.server.index.account.AccountIndexCollection) Sets(com.google.common.collect.Sets) GroupReference(com.google.gerrit.entities.GroupReference) Objects(java.util.Objects) TooManyTermsInQueryException(com.google.gerrit.index.query.TooManyTermsInQueryException) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) Url(com.google.gerrit.extensions.restapi.Url) MetricMaker(com.google.gerrit.metrics.MetricMaker) LazyArgs.lazy(com.google.common.flogger.LazyArgs.lazy) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) AccountLoader(com.google.gerrit.server.account.AccountLoader) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) IndexConfig(com.google.gerrit.index.IndexConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ReviewerState(com.google.gerrit.extensions.client.ReviewerState) ResultSet(com.google.gerrit.index.query.ResultSet) AccountPredicates(com.google.gerrit.server.query.account.AccountPredicates) GroupMembers(com.google.gerrit.server.account.GroupMembers) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) ImmutableList(com.google.common.collect.ImmutableList) QueryParseException(com.google.gerrit.index.query.QueryParseException) Description(com.google.gerrit.metrics.Description) FieldBundle(com.google.gerrit.index.query.FieldBundle) AccountIndexRewriter(com.google.gerrit.server.index.account.AccountIndexRewriter) Predicate(com.google.gerrit.index.query.Predicate) SuggestedReviewerInfo(com.google.gerrit.extensions.common.SuggestedReviewerInfo) AccountControl(com.google.gerrit.server.account.AccountControl) CurrentUser(com.google.gerrit.server.CurrentUser) AccountField(com.google.gerrit.server.index.account.AccountField) StorageException(com.google.gerrit.exceptions.StorageException) Units(com.google.gerrit.metrics.Description.Units) ProjectState(com.google.gerrit.server.project.ProjectState) QueryOptions(com.google.gerrit.index.QueryOptions) NoSuchProjectException(com.google.gerrit.server.project.NoSuchProjectException) ChangeNotes(com.google.gerrit.server.notedb.ChangeNotes) IOException(java.io.IOException) Collectors.toList(java.util.stream.Collectors.toList) Provider(com.google.inject.Provider) Project(com.google.gerrit.entities.Project) AccountState(com.google.gerrit.server.account.AccountState) ServiceUserClassifier(com.google.gerrit.server.account.ServiceUserClassifier) Collections(java.util.Collections) TooManyTermsInQueryException(com.google.gerrit.index.query.TooManyTermsInQueryException) FieldBundle(com.google.gerrit.index.query.FieldBundle) AccountState(com.google.gerrit.server.account.AccountState) QueryParseException(com.google.gerrit.index.query.QueryParseException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) Timer0(com.google.gerrit.metrics.Timer0) StorageException(com.google.gerrit.exceptions.StorageException)

Example 39 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class FakeAccountCache method put.

public synchronized void put(Account account) {
    AccountState state = newState(account);
    byId.put(account.id(), state);
}
Also used : AccountState(com.google.gerrit.server.account.AccountState)

Example 40 with AccountState

use of com.google.gerrit.server.account.AccountState in project gerrit by GerritCodeReview.

the class PostGpgKeys method getAccountByExternalId.

private Account getAccountByExternalId(ExternalId.Key extIdKey) {
    List<AccountState> accountStates = accountQueryProvider.get().byExternalId(extIdKey);
    if (accountStates.isEmpty()) {
        return null;
    }
    if (accountStates.size() > 1) {
        String msg = "GPG key " + extIdKey.get() + " associated with multiple accounts: [";
        msg = accountStates.stream().map(a -> a.account().id().toString()).collect(joining(", ", msg, "]"));
        throw new IllegalStateException(msg);
    }
    return accountStates.get(0).account();
}
Also used : AccountState(com.google.gerrit.server.account.AccountState) PublicKeyStore.keyToString(com.google.gerrit.gpg.PublicKeyStore.keyToString) PublicKeyStore.keyIdToString(com.google.gerrit.gpg.PublicKeyStore.keyIdToString)

Aggregations

AccountState (com.google.gerrit.server.account.AccountState)63 Account (com.google.gerrit.entities.Account)37 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)18 IOException (java.io.IOException)17 Test (org.junit.Test)16 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)15 Inject (com.google.inject.Inject)15 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)14 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 ArrayList (java.util.ArrayList)12 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)11 HashSet (java.util.HashSet)11 List (java.util.List)11 ImmutableSet (com.google.common.collect.ImmutableSet)10 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)10 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)10 AccountsUpdate (com.google.gerrit.server.account.AccountsUpdate)10 TestAccount (com.google.gerrit.acceptance.TestAccount)9 Nullable (com.google.gerrit.common.Nullable)9 StorageException (com.google.gerrit.exceptions.StorageException)9