Search in sources :

Example 16 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class PostReview method batchEmailReviewers.

private void batchEmailReviewers(CurrentUser user, Change change, List<ReviewerModification> reviewerModifications, NotifyResolver.Result notify) {
    try (TraceContext.TraceTimer ignored = newTimer("batchEmailReviewers")) {
        List<Account.Id> to = new ArrayList<>();
        List<Account.Id> cc = new ArrayList<>();
        List<Account.Id> removed = new ArrayList<>();
        List<Address> toByEmail = new ArrayList<>();
        List<Address> ccByEmail = new ArrayList<>();
        List<Address> removedByEmail = new ArrayList<>();
        for (ReviewerModification modification : reviewerModifications) {
            Result reviewAdditionResult = modification.op.getResult();
            if (modification.state() == ReviewerState.REVIEWER && (!reviewAdditionResult.addedReviewers().isEmpty() || !reviewAdditionResult.addedReviewersByEmail().isEmpty())) {
                to.addAll(modification.reviewers.stream().map(Account::id).collect(toImmutableSet()));
                toByEmail.addAll(modification.reviewersByEmail);
            } else if (modification.state() == ReviewerState.CC && (!reviewAdditionResult.addedCCs().isEmpty() || !reviewAdditionResult.addedCCsByEmail().isEmpty())) {
                cc.addAll(modification.reviewers.stream().map(Account::id).collect(toImmutableSet()));
                ccByEmail.addAll(modification.reviewersByEmail);
            } else if (modification.state() == ReviewerState.REMOVED && (reviewAdditionResult.deletedReviewer().isPresent() || reviewAdditionResult.deletedReviewerByEmail().isPresent())) {
                reviewAdditionResult.deletedReviewer().ifPresent(d -> removed.add(d));
                reviewAdditionResult.deletedReviewerByEmail().ifPresent(d -> removedByEmail.add(d));
            }
        }
        modifyReviewersEmail.emailReviewersAsync(user.asIdentifiedUser(), change, to, cc, removed, toByEmail, ccByEmail, removedByEmail, notify);
    }
}
Also used : Account(com.google.gerrit.entities.Account) Address(com.google.gerrit.entities.Address) ArrayList(java.util.ArrayList) TraceContext(com.google.gerrit.server.logging.TraceContext) ReviewerModification(com.google.gerrit.server.change.ReviewerModifier.ReviewerModification) ObjectId(org.eclipse.jgit.lib.ObjectId) ReviewResult(com.google.gerrit.extensions.api.changes.ReviewResult) ReviewerResult(com.google.gerrit.extensions.api.changes.ReviewerResult) Result(com.google.gerrit.server.change.ReviewerOp.Result)

Example 17 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class RefVisibilityControl method isVisible.

/**
 * Returns an authoritative answer if the ref is visible to the user. Does not have support for
 * tags and will throw a {@link PermissionBackendException} if asked for tags visibility.
 */
boolean isVisible(ProjectControl projectControl, String refName) throws PermissionBackendException {
    if (refName.startsWith(Constants.R_TAGS)) {
        throw new PermissionBackendException("can't check tags through RefVisibilityControl. Use PermissionBackend#filter instead.");
    }
    if (!RefNames.isGerritRef(refName)) {
        // refs/heads or another ref the user created. Apply the regular permissions with inheritance.
        return projectControl.controlForRef(refName).hasReadPermissionOnRef(false);
    }
    if (refName.startsWith(REFS_CACHE_AUTOMERGE)) {
        // Internal cache state that is accessible to no one.
        return false;
    }
    boolean hasAccessDatabase = permissionBackend.user(projectControl.getUser()).testOrFalse(GlobalPermission.ACCESS_DATABASE);
    if (hasAccessDatabase) {
        return true;
    }
    // Change and change edit visibility
    Change.Id changeId;
    if ((changeId = Change.Id.fromRef(refName)) != null) {
        // Change ref is visible only if the change is visible.
        ChangeData cd;
        try {
            cd = changeDataFactory.create(projectControl.getProject().getNameKey(), changeId);
            checkState(cd.change().getId().equals(changeId));
        } catch (StorageException e) {
            if (Throwables.getCausalChain(e).stream().anyMatch(e2 -> e2 instanceof NoSuchChangeException)) {
                // The change was deleted or is otherwise not accessible anymore.
                // If the caller can see all refs and is allowed to see private changes on refs/, allow
                // access. This is an escape hatch for receivers of "ref deleted" events.
                PermissionBackend.ForProject forProject = projectControl.asForProject();
                return forProject.test(ProjectPermission.READ) && forProject.ref("refs/").test(RefPermission.READ_PRIVATE_CHANGES);
            }
            throw new PermissionBackendException(e);
        }
        if (RefNames.isRefsEdit(refName)) {
            // Edits are visible only to the owning user, if change is visible.
            return visibleEdit(refName, projectControl, cd);
        }
        return projectControl.controlFor(cd).isVisible();
    }
    // Account visibility
    CurrentUser user = projectControl.getUser();
    Account.Id currentUserAccountId = user.isIdentifiedUser() ? user.getAccountId() : null;
    Account.Id accountId;
    if ((accountId = Account.Id.fromRef(refName)) != null) {
        // Account ref is visible only to the corresponding account.
        if (accountId.equals(currentUserAccountId)) {
            // refs, check if the user has read permissions.
            if (RefNames.isRefsDraftsComments(refName) || RefNames.isRefsStarredChanges(refName) || projectControl.controlForRef(refName).hasReadPermissionOnRef(true)) {
                return true;
            }
        }
        return false;
    }
    // Group visibility
    AccountGroup.UUID accountGroupUuid;
    if ((accountGroupUuid = AccountGroup.UUID.fromRef(refName)) != null) {
        // Group ref is visible only to the corresponding owner group.
        try {
            return projectControl.controlForRef(refName).hasReadPermissionOnRef(true) && groupControlFactory.controlFor(user, accountGroupUuid).isOwner();
        } catch (NoSuchGroupException e) {
            // The group is broken, but the ref is still around. Pretend the ref is not visible.
            logger.atWarning().withCause(e).log("Found group ref %s but group isn't parsable", refName);
            return false;
        }
    }
    // We are done checking all cases where we would allow access to Gerrit-managed refs. Deny
    // access in case we got this far.
    logger.atFine().log("Denying access to %s because user doesn't have access to this Gerrit ref", refName);
    return false;
}
Also used : AccountGroup(com.google.gerrit.entities.AccountGroup) CurrentUser(com.google.gerrit.server.CurrentUser) GroupControl(com.google.gerrit.server.account.GroupControl) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) StorageException(com.google.gerrit.exceptions.StorageException) Throwables(com.google.common.base.Throwables) Account(com.google.gerrit.entities.Account) Constants(org.eclipse.jgit.lib.Constants) Singleton(javax.inject.Singleton) Preconditions.checkState(com.google.common.base.Preconditions.checkState) Inject(javax.inject.Inject) ChangeData(com.google.gerrit.server.query.change.ChangeData) REFS_CACHE_AUTOMERGE(com.google.gerrit.entities.RefNames.REFS_CACHE_AUTOMERGE) RefNames(com.google.gerrit.entities.RefNames) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) Change(com.google.gerrit.entities.Change) FluentLogger(com.google.common.flogger.FluentLogger) Account(com.google.gerrit.entities.Account) CurrentUser(com.google.gerrit.server.CurrentUser) Change(com.google.gerrit.entities.Change) ChangeData(com.google.gerrit.server.query.change.ChangeData) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) NoSuchChangeException(com.google.gerrit.server.project.NoSuchChangeException) AccountGroup(com.google.gerrit.entities.AccountGroup) StorageException(com.google.gerrit.exceptions.StorageException)

Example 18 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class GroupConfigTest method commitMessageFootersCanBeMixed.

@Test
public void commitMessageFootersCanBeMixed() throws Exception {
    Account account13 = createAccount(Account.id(13), "John");
    Account account7 = createAccount(Account.id(7), "Jane");
    ImmutableSet<Account> accounts = ImmutableSet.of(account13, account7);
    GroupDescription.Basic group1 = createGroup(AccountGroup.uuid("129403"), "Bots");
    GroupDescription.Basic group2 = createGroup(AccountGroup.uuid("8903493"), "Verifiers");
    ImmutableSet<GroupDescription.Basic> groups = ImmutableSet.of(group1, group2);
    createArbitraryGroup(groupUuid);
    AuditLogFormatter auditLogFormatter = AuditLogFormatter.createBackedBy(accounts, groups, "serverId");
    GroupDelta groupDelta1 = GroupDelta.builder().setName(AccountGroup.nameKey("Old name")).setMemberModification(members -> ImmutableSet.of(account7.id())).setSubgroupModification(subgroups -> ImmutableSet.of(group2.getGroupUUID())).build();
    updateGroup(groupUuid, groupDelta1, auditLogFormatter);
    GroupDelta groupDelta2 = GroupDelta.builder().setName(AccountGroup.nameKey("New name")).setMemberModification(members -> ImmutableSet.of(account13.id())).setSubgroupModification(subgroups -> ImmutableSet.of(group1.getGroupUUID())).build();
    updateGroup(groupUuid, groupDelta2, auditLogFormatter);
    RevCommit revCommit = getLatestCommitForGroup(groupUuid);
    assertThat(revCommit.getFullMessage()).isEqualTo("Update group\n" + "\n" + "Add-group: Bots <129403>\n" + "Add: John <13@serverId>\n" + "Remove-group: Verifiers <8903493>\n" + "Remove: Jane <7@serverId>\n" + "Rename from Old name to New name");
}
Also used : GroupDescription(com.google.gerrit.entities.GroupDescription) InternalGroup(com.google.gerrit.entities.InternalGroup) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) Date(java.util.Date) LocalDateTime(java.time.LocalDateTime) OptionalSubject.assertThat(com.google.gerrit.truth.OptionalSubject.assertThat) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) RevWalk(org.eclipse.jgit.revwalk.RevWalk) GroupDescription(com.google.gerrit.entities.GroupDescription) RefNames(com.google.gerrit.entities.RefNames) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) AccountGroup(com.google.gerrit.entities.AccountGroup) DfsRepositoryDescription(org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription) TestRepository(org.eclipse.jgit.junit.TestRepository) ImmutableSet(com.google.common.collect.ImmutableSet) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Month(java.time.Month) TimeZone(java.util.TimeZone) Account(com.google.gerrit.entities.Account) InternalGroupSubject(com.google.gerrit.server.group.testing.InternalGroupSubject) IOException(java.io.IOException) Test(org.junit.Test) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) ZoneId(java.time.ZoneId) PersonIdent(org.eclipse.jgit.lib.PersonIdent) Nullable(com.google.gerrit.common.Nullable) OptionalSubject(com.google.gerrit.truth.OptionalSubject) LocalDate(java.time.LocalDate) Ref(org.eclipse.jgit.lib.Ref) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) GerritJUnit.assertThrows(com.google.gerrit.testing.GerritJUnit.assertThrows) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) InternalGroupSubject.internalGroups(com.google.gerrit.server.group.testing.InternalGroupSubject.internalGroups) GitReferenceUpdated(com.google.gerrit.server.extensions.events.GitReferenceUpdated) Repository(org.eclipse.jgit.lib.Repository) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate) Account(com.google.gerrit.entities.Account) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 19 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class AuditLogReaderTest method addAndRemoveMembersAndSubgroups.

@Test
public void addAndRemoveMembersAndSubgroups() throws Exception {
    InternalGroup group = createGroupAsUser(1, "test-group");
    AccountGroup.Id groupId = group.getId();
    AccountGroup.UUID uuid = group.getGroupUUID();
    AccountGroupMemberAudit expMemberAudit = createExpMemberAudit(groupId, userId, userId, getTipTimestamp(uuid));
    assertThat(auditLogReader.getMembersAudit(allUsersRepo, uuid)).containsExactly(expMemberAudit);
    Account.Id id1 = Account.id(100002);
    Account.Id id2 = Account.id(100003);
    Account.Id id3 = Account.id(100004);
    InternalGroup subgroup1 = createGroupAsUser(2, "test-group-2");
    InternalGroup subgroup2 = createGroupAsUser(3, "test-group-3");
    InternalGroup subgroup3 = createGroupAsUser(4, "test-group-4");
    AccountGroup.UUID subgroupUuid1 = subgroup1.getGroupUUID();
    AccountGroup.UUID subgroupUuid2 = subgroup2.getGroupUUID();
    AccountGroup.UUID subgroupUuid3 = subgroup3.getGroupUUID();
    // Add two accounts.
    addMembers(uuid, ImmutableSet.of(id1, id2));
    AccountGroupMemberAudit expMemberAudit1 = createExpMemberAudit(groupId, id1, userId, getTipTimestamp(uuid));
    AccountGroupMemberAudit expMemberAudit2 = createExpMemberAudit(groupId, id2, userId, getTipTimestamp(uuid));
    assertThat(auditLogReader.getMembersAudit(allUsersRepo, uuid)).containsExactly(expMemberAudit, expMemberAudit1, expMemberAudit2).inOrder();
    // Add one subgroup.
    addSubgroups(uuid, ImmutableSet.of(subgroupUuid1));
    AccountGroupByIdAudit expGroupAudit1 = createExpGroupAudit(group.getId(), subgroupUuid1, userId, getTipTimestamp(uuid));
    assertThat(auditLogReader.getSubgroupsAudit(allUsersRepo, uuid)).containsExactly(expGroupAudit1);
    // Remove one account.
    removeMembers(uuid, ImmutableSet.of(id2));
    expMemberAudit2 = expMemberAudit2.toBuilder().removed(userId, getTipTimestamp(uuid)).build();
    assertThat(auditLogReader.getMembersAudit(allUsersRepo, uuid)).containsExactly(expMemberAudit, expMemberAudit1, expMemberAudit2).inOrder();
    // Add two subgroups.
    addSubgroups(uuid, ImmutableSet.of(subgroupUuid2, subgroupUuid3));
    AccountGroupByIdAudit expGroupAudit2 = createExpGroupAudit(group.getId(), subgroupUuid2, userId, getTipTimestamp(uuid));
    AccountGroupByIdAudit expGroupAudit3 = createExpGroupAudit(group.getId(), subgroupUuid3, userId, getTipTimestamp(uuid));
    assertThat(auditLogReader.getSubgroupsAudit(allUsersRepo, uuid)).containsExactly(expGroupAudit1, expGroupAudit2, expGroupAudit3).inOrder();
    // Add two account, including a removed account.
    addMembers(uuid, ImmutableSet.of(id2, id3));
    AccountGroupMemberAudit expMemberAudit4 = createExpMemberAudit(groupId, id2, userId, getTipTimestamp(uuid));
    AccountGroupMemberAudit expMemberAudit3 = createExpMemberAudit(groupId, id3, userId, getTipTimestamp(uuid));
    assertThat(auditLogReader.getMembersAudit(allUsersRepo, uuid)).containsExactly(expMemberAudit, expMemberAudit1, expMemberAudit2, expMemberAudit4, expMemberAudit3).inOrder();
    // Remove two subgroups.
    removeSubgroups(uuid, ImmutableSet.of(subgroupUuid1, subgroupUuid3));
    expGroupAudit1 = expGroupAudit1.toBuilder().removed(userId, getTipTimestamp(uuid)).build();
    expGroupAudit3 = expGroupAudit3.toBuilder().removed(userId, getTipTimestamp(uuid)).build();
    assertThat(auditLogReader.getSubgroupsAudit(allUsersRepo, uuid)).containsExactly(expGroupAudit1, expGroupAudit2, expGroupAudit3).inOrder();
    // Add back one removed subgroup.
    addSubgroups(uuid, ImmutableSet.of(subgroupUuid1));
    AccountGroupByIdAudit expGroupAudit4 = createExpGroupAudit(group.getId(), subgroupUuid1, userId, getTipTimestamp(uuid));
    assertThat(auditLogReader.getSubgroupsAudit(allUsersRepo, uuid)).containsExactly(expGroupAudit1, expGroupAudit2, expGroupAudit3, expGroupAudit4).inOrder();
}
Also used : Account(com.google.gerrit.entities.Account) AccountGroup(com.google.gerrit.entities.AccountGroup) AccountGroupMemberAudit(com.google.gerrit.entities.AccountGroupMemberAudit) AccountGroupByIdAudit(com.google.gerrit.entities.AccountGroupByIdAudit) InternalGroup(com.google.gerrit.entities.InternalGroup) Test(org.junit.Test)

Example 20 with Account

use of com.google.gerrit.entities.Account in project gerrit by GerritCodeReview.

the class GroupConfigTest method commitMessageOfMemberAdditionContainsFooters.

@Test
public void commitMessageOfMemberAdditionContainsFooters() throws Exception {
    Account account13 = createAccount(Account.id(13), "John");
    Account account7 = createAccount(Account.id(7), "Jane");
    ImmutableSet<Account> accounts = ImmutableSet.of(account13, account7);
    createArbitraryGroup(groupUuid);
    AuditLogFormatter auditLogFormatter = AuditLogFormatter.createBackedBy(accounts, ImmutableSet.of(), "GerritServer1");
    GroupDelta groupDelta = GroupDelta.builder().setMemberModification(members -> ImmutableSet.of(account13.id(), account7.id())).build();
    updateGroup(groupUuid, groupDelta, auditLogFormatter);
    RevCommit revCommit = getLatestCommitForGroup(groupUuid);
    assertThat(revCommit.getFullMessage()).isEqualTo("Update group\n\nAdd: Jane <7@GerritServer1>\nAdd: John <13@GerritServer1>");
}
Also used : InternalGroup(com.google.gerrit.entities.InternalGroup) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) RevCommit(org.eclipse.jgit.revwalk.RevCommit) InMemoryRepository(org.eclipse.jgit.internal.storage.dfs.InMemoryRepository) Date(java.util.Date) LocalDateTime(java.time.LocalDateTime) OptionalSubject.assertThat(com.google.gerrit.truth.OptionalSubject.assertThat) CoreMatchers.instanceOf(org.hamcrest.CoreMatchers.instanceOf) RevWalk(org.eclipse.jgit.revwalk.RevWalk) GroupDescription(com.google.gerrit.entities.GroupDescription) RefNames(com.google.gerrit.entities.RefNames) MatcherAssert.assertThat(org.hamcrest.MatcherAssert.assertThat) Before(org.junit.Before) AccountGroup(com.google.gerrit.entities.AccountGroup) DfsRepositoryDescription(org.eclipse.jgit.internal.storage.dfs.DfsRepositoryDescription) TestRepository(org.eclipse.jgit.junit.TestRepository) ImmutableSet(com.google.common.collect.ImmutableSet) Truth.assertWithMessage(com.google.common.truth.Truth.assertWithMessage) Month(java.time.Month) TimeZone(java.util.TimeZone) Account(com.google.gerrit.entities.Account) InternalGroupSubject(com.google.gerrit.server.group.testing.InternalGroupSubject) IOException(java.io.IOException) Test(org.junit.Test) Truth.assertThat(com.google.common.truth.Truth.assertThat) Instant(java.time.Instant) Sets(com.google.common.collect.Sets) ZoneId(java.time.ZoneId) PersonIdent(org.eclipse.jgit.lib.PersonIdent) Nullable(com.google.gerrit.common.Nullable) OptionalSubject(com.google.gerrit.truth.OptionalSubject) LocalDate(java.time.LocalDate) Ref(org.eclipse.jgit.lib.Ref) Project(com.google.gerrit.entities.Project) Optional(java.util.Optional) GerritJUnit.assertThrows(com.google.gerrit.testing.GerritJUnit.assertThrows) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) InternalGroupSubject.internalGroups(com.google.gerrit.server.group.testing.InternalGroupSubject.internalGroups) GitReferenceUpdated(com.google.gerrit.server.extensions.events.GitReferenceUpdated) Repository(org.eclipse.jgit.lib.Repository) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate) Account(com.google.gerrit.entities.Account) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Aggregations

Account (com.google.gerrit.entities.Account)124 Test (org.junit.Test)59 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)37 AbstractDaemonTest (com.google.gerrit.acceptance.AbstractDaemonTest)35 AccountState (com.google.gerrit.server.account.AccountState)35 IOException (java.io.IOException)31 Repository (org.eclipse.jgit.lib.Repository)31 Change (com.google.gerrit.entities.Change)28 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)26 Inject (com.google.inject.Inject)25 PersonIdent (org.eclipse.jgit.lib.PersonIdent)25 List (java.util.List)24 ArrayList (java.util.ArrayList)23 HashSet (java.util.HashSet)23 Set (java.util.Set)22 RefNames (com.google.gerrit.entities.RefNames)21 AuthRequest (com.google.gerrit.server.account.AuthRequest)21 Map (java.util.Map)21 ObjectId (org.eclipse.jgit.lib.ObjectId)21 ImmutableList (com.google.common.collect.ImmutableList)20