Search in sources :

Example 6 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class AgreementJson method format.

public AgreementInfo format(ContributorAgreement ca) throws PermissionBackendException {
    AgreementInfo info = new AgreementInfo();
    info.name = ca.getName();
    info.description = ca.getDescription();
    info.url = ca.getAgreementUrl();
    GroupReference autoVerifyGroup = ca.getAutoVerify();
    if (autoVerifyGroup != null && self.get().isIdentifiedUser()) {
        IdentifiedUser user = identifiedUserFactory.create(self.get().getAccountId());
        try {
            GroupControl gc = genericGroupControlFactory.controlFor(user, autoVerifyGroup.getUUID());
            GroupResource group = new GroupResource(gc);
            info.autoVerifyGroup = groupJson.format(group);
        } catch (NoSuchGroupException | StorageException e) {
            logger.atWarning().log("autoverify group \"%s\" does not exist, referenced in CLA \"%s\"", autoVerifyGroup.getName(), ca.getName());
        }
    }
    return info;
}
Also used : GroupControl(com.google.gerrit.server.account.GroupControl) AgreementInfo(com.google.gerrit.extensions.common.AgreementInfo) GroupReference(com.google.gerrit.entities.GroupReference) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) StorageException(com.google.gerrit.exceptions.StorageException) GroupResource(com.google.gerrit.server.group.GroupResource) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException)

Example 7 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class DeleteMembers method removeGroupMembers.

private void removeGroupMembers(AccountGroup.UUID groupUuid, Set<Account.Id> accountIds) throws IOException, NoSuchGroupException, ConfigInvalidException {
    GroupDelta groupDelta = GroupDelta.builder().setMemberModification(memberIds -> Sets.difference(memberIds, accountIds)).build();
    groupsUpdateProvider.get().updateGroup(groupUuid, groupDelta);
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) GroupResource(com.google.gerrit.server.group.GroupResource) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) Inject(com.google.inject.Inject) Response(com.google.gerrit.extensions.restapi.Response) MemberResource(com.google.gerrit.server.group.MemberResource) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) GroupsUpdate(com.google.gerrit.server.group.db.GroupsUpdate) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) GroupDescription(com.google.gerrit.entities.GroupDescription) AuthException(com.google.gerrit.extensions.restapi.AuthException) AccountGroup(com.google.gerrit.entities.AccountGroup) Input(com.google.gerrit.server.restapi.group.AddMembers.Input) GroupControl(com.google.gerrit.server.account.GroupControl) AccountResolver(com.google.gerrit.server.account.AccountResolver) Account(com.google.gerrit.entities.Account) Set(java.util.Set) IOException(java.io.IOException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) Sets(com.google.common.collect.Sets) Provider(com.google.inject.Provider) UserInitiated(com.google.gerrit.server.UserInitiated) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) Singleton(com.google.inject.Singleton) GroupDelta(com.google.gerrit.server.group.db.GroupDelta)

Example 8 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException 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 9 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class ListProjects method display.

@Nullable
public SortedMap<String, ProjectInfo> display(@Nullable PrintWriter stdout) throws BadRequestException, PermissionBackendException {
    if (all && state != null) {
        throw new BadRequestException("'all' and 'state' may not be used together");
    }
    if (groupUuid != null) {
        try {
            if (!groupControlFactory.controlFor(groupUuid).isVisible()) {
                return Collections.emptySortedMap();
            }
        } catch (NoSuchGroupException ex) {
            return Collections.emptySortedMap();
        }
    }
    int foundIndex = 0;
    int found = 0;
    TreeMap<String, ProjectInfo> output = new TreeMap<>();
    Map<String, String> hiddenNames = new HashMap<>();
    Map<Project.NameKey, Boolean> accessibleParents = new HashMap<>();
    PermissionBackend.WithUser perm = permissionBackend.user(currentUser);
    final TreeMap<Project.NameKey, ProjectNode> treeMap = new TreeMap<>();
    try {
        Iterator<ProjectState> projectStatesIt = filter(perm).iterator();
        while (projectStatesIt.hasNext()) {
            ProjectState e = projectStatesIt.next();
            Project.NameKey projectName = e.getNameKey();
            if (e.getProject().getState() == HIDDEN && !all && state != HIDDEN) {
                // If state HIDDEN wasn't selected, and it's HIDDEN, pretend it's not present.
                continue;
            }
            if (state != null && e.getProject().getState() != state) {
                continue;
            }
            if (groupUuid != null && !e.getLocalGroups().contains(GroupReference.forGroup(groupResolver.parseId(groupUuid.get())))) {
                continue;
            }
            if (showTree && !format.isJson()) {
                treeMap.put(projectName, projectNodeFactory.create(e.getProject(), true));
                continue;
            }
            if (foundIndex++ < start) {
                continue;
            }
            if (limit > 0 && ++found > limit) {
                break;
            }
            ProjectInfo info = new ProjectInfo();
            info.name = projectName.get();
            if (showTree && format.isJson()) {
                addParentProjectInfo(hiddenNames, accessibleParents, perm, e, info);
            }
            if (showDescription) {
                info.description = emptyToNull(e.getProject().getDescription());
            }
            info.state = e.getProject().getState();
            try {
                if (!showBranch.isEmpty()) {
                    try (Repository git = repoManager.openRepository(projectName)) {
                        if (!type.matches(git)) {
                            continue;
                        }
                        List<Ref> refs = retrieveBranchRefs(e, git);
                        if (!hasValidRef(refs)) {
                            continue;
                        }
                        addProjectBranchesInfo(info, refs);
                    }
                } else if (!showTree && type.useMatch()) {
                    try (Repository git = repoManager.openRepository(projectName)) {
                        if (!type.matches(git)) {
                            continue;
                        }
                    }
                }
            } catch (RepositoryNotFoundException err) {
                // If the Git repository is gone, the project doesn't actually exist anymore.
                continue;
            } catch (IOException err) {
                logger.atWarning().withCause(err).log("Unexpected error reading %s", projectName);
                continue;
            }
            ImmutableList<WebLinkInfo> links = webLinks.getProjectLinks(projectName.get());
            info.webLinks = links.isEmpty() ? null : links;
            if (stdout == null || format.isJson()) {
                output.put(info.name, info);
                continue;
            }
            if (!showBranch.isEmpty()) {
                printProjectBranches(stdout, info);
            }
            stdout.print(info.name);
            if (info.description != null) {
                // We still want to list every project as one-liners, hence escaping \n.
                stdout.print(" - " + StringUtil.escapeString(info.description));
            }
            stdout.print('\n');
        }
        for (ProjectInfo info : output.values()) {
            info.id = Url.encode(info.name);
            info.name = null;
        }
        if (stdout == null) {
            return output;
        } else if (format.isJson()) {
            format.newGson().toJson(output, new TypeToken<Map<String, ProjectInfo>>() {
            }.getType(), stdout);
            stdout.print('\n');
        } else if (showTree && treeMap.size() > 0) {
            printProjectTree(stdout, treeMap);
        }
        return null;
    } finally {
        if (stdout != null) {
            stdout.flush();
        }
    }
}
Also used : HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) ProjectInfo(com.google.gerrit.extensions.common.ProjectInfo) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) IOException(java.io.IOException) TreeMap(java.util.TreeMap) Project(com.google.gerrit.entities.Project) Repository(org.eclipse.jgit.lib.Repository) Ref(org.eclipse.jgit.lib.Ref) WebLinkInfo(com.google.gerrit.extensions.common.WebLinkInfo) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ProjectState(com.google.gerrit.server.project.ProjectState) Map(java.util.Map) SortedMap(java.util.SortedMap) HashMap(java.util.HashMap) LinkedHashMap(java.util.LinkedHashMap) ImmutableSortedMap(com.google.common.collect.ImmutableSortedMap) TreeMap(java.util.TreeMap) Nullable(com.google.gerrit.common.Nullable)

Example 10 with NoSuchGroupException

use of com.google.gerrit.exceptions.NoSuchGroupException in project gerrit by GerritCodeReview.

the class GetGroups method apply.

@Override
public Response<List<GroupInfo>> apply(AccountResource resource) throws PermissionBackendException {
    IdentifiedUser user = resource.getUser();
    Account.Id userId = user.getAccountId();
    Set<AccountGroup.UUID> knownGroups = user.getEffectiveGroups().getKnownGroups();
    List<GroupInfo> visibleGroups = new ArrayList<>();
    for (AccountGroup.UUID uuid : knownGroups) {
        GroupControl ctl;
        try {
            ctl = groupControlFactory.controlFor(uuid);
        } catch (NoSuchGroupException e) {
            logger.atFine().log("skipping non-existing group %s", uuid);
            continue;
        }
        if (!ctl.isVisible()) {
            logger.atFine().log("skipping non-visible group %s", uuid);
            continue;
        }
        if (!ctl.canSeeMember(userId)) {
            logger.atFine().log("skipping group %s because member %d cannot be seen", uuid, userId.get());
            continue;
        }
        visibleGroups.add(json.format(ctl.getGroup()));
    }
    return Response.ok(visibleGroups);
}
Also used : GroupControl(com.google.gerrit.server.account.GroupControl) Account(com.google.gerrit.entities.Account) AccountGroup(com.google.gerrit.entities.AccountGroup) GroupInfo(com.google.gerrit.extensions.common.GroupInfo) ArrayList(java.util.ArrayList) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException)

Aggregations

NoSuchGroupException (com.google.gerrit.exceptions.NoSuchGroupException)26 AccountGroup (com.google.gerrit.entities.AccountGroup)22 GroupDescription (com.google.gerrit.entities.GroupDescription)13 AuthException (com.google.gerrit.extensions.restapi.AuthException)12 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)12 GroupControl (com.google.gerrit.server.account.GroupControl)12 GroupDelta (com.google.gerrit.server.group.db.GroupDelta)12 Account (com.google.gerrit.entities.Account)10 ArrayList (java.util.ArrayList)10 Inject (com.google.inject.Inject)9 IOException (java.io.IOException)9 Singleton (com.google.inject.Singleton)8 Sets (com.google.common.collect.Sets)7 UnprocessableEntityException (com.google.gerrit.extensions.restapi.UnprocessableEntityException)7 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)7 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)6 IdString (com.google.gerrit.extensions.restapi.IdString)6 Response (com.google.gerrit.extensions.restapi.Response)6 GroupResource (com.google.gerrit.server.group.GroupResource)6 GroupsUpdate (com.google.gerrit.server.group.db.GroupsUpdate)6