Search in sources :

Example 11 with PermissionRule

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

the class ProjectConfig method saveAccessSections.

private void saveAccessSections(Config rc, Set<AccountGroup.UUID> keepGroups) {
    unsetSection(rc, CAPABILITY);
    AccessSection capability = accessSections.get(AccessSection.GLOBAL_CAPABILITIES);
    if (capability != null) {
        Set<String> have = new HashSet<>();
        for (Permission permission : sort(capability.getPermissions())) {
            have.add(permission.getName().toLowerCase());
            boolean needRange = GlobalCapability.hasRange(permission.getName());
            List<String> rules = new ArrayList<>();
            for (PermissionRule rule : sort(permission.getRules())) {
                GroupReference group = resolve(rule.getGroup());
                if (group.getUUID() != null) {
                    keepGroups.add(group.getUUID());
                }
                rules.add(rule.toBuilder().setGroup(group).build().asString(needRange));
            }
            rc.setStringList(CAPABILITY, null, permission.getName(), rules);
        }
        for (String varName : rc.getNames(CAPABILITY)) {
            if (!have.contains(varName.toLowerCase())) {
                rc.unset(CAPABILITY, null, varName);
            }
        }
    } else {
        rc.unsetSection(CAPABILITY, null);
    }
    for (AccessSection as : sort(accessSections.values())) {
        String refName = as.getName();
        if (AccessSection.GLOBAL_CAPABILITIES.equals(refName)) {
            continue;
        }
        StringBuilder doNotInherit = new StringBuilder();
        for (Permission perm : sort(as.getPermissions())) {
            if (perm.getExclusiveGroup()) {
                if (0 < doNotInherit.length()) {
                    doNotInherit.append(' ');
                }
                doNotInherit.append(perm.getName());
            }
        }
        if (0 < doNotInherit.length()) {
            rc.setString(ACCESS, refName, KEY_GROUP_PERMISSIONS, doNotInherit.toString());
        } else {
            rc.unset(ACCESS, refName, KEY_GROUP_PERMISSIONS);
        }
        Set<String> have = new HashSet<>();
        for (Permission permission : sort(as.getPermissions())) {
            have.add(permission.getName().toLowerCase());
            boolean needRange = Permission.hasRange(permission.getName());
            List<String> rules = new ArrayList<>();
            for (PermissionRule rule : sort(permission.getRules())) {
                GroupReference group = resolve(rule.getGroup());
                if (group.getUUID() != null) {
                    keepGroups.add(group.getUUID());
                }
                rules.add(rule.toBuilder().setGroup(group).build().asString(needRange));
            }
            rc.setStringList(ACCESS, refName, permission.getName(), rules);
        }
        for (String varName : rc.getNames(ACCESS, refName)) {
            if (isCoreOrPluginPermission(convertLegacyPermission(varName)) && !have.contains(varName.toLowerCase())) {
                rc.unset(ACCESS, refName, varName);
            }
        }
    }
    for (String name : rc.getSubsections(ACCESS)) {
        if (AccessSection.isValidRefSectionName(name) && !accessSections.containsKey(name)) {
            rc.unsetSection(ACCESS, name);
        }
    }
}
Also used : PermissionRule(com.google.gerrit.entities.PermissionRule) Permission.isPermission(com.google.gerrit.entities.Permission.isPermission) PluginPermissionsUtil.isValidPluginPermission(com.google.gerrit.server.permissions.PluginPermissionsUtil.isValidPluginPermission) Permission(com.google.gerrit.entities.Permission) ArrayList(java.util.ArrayList) GroupReference(com.google.gerrit.entities.GroupReference) AccessSection(com.google.gerrit.entities.AccessSection) HashSet(java.util.HashSet)

Example 12 with PermissionRule

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

the class AgreementsIT method configureContributorAgreement.

protected ContributorAgreement configureContributorAgreement(boolean autoVerify) throws Exception {
    ContributorAgreement.Builder ca;
    String name = autoVerify ? "cla-test-group" : "cla-test-no-auto-verify-group";
    AccountGroup.UUID g = groupOperations.newGroup().name(name).create();
    GroupApi groupApi = gApi.groups().id(g.get());
    groupApi.description("CLA test group");
    InternalGroup caGroup = group(AccountGroup.uuid(groupApi.detail().id));
    GroupReference groupRef = GroupReference.create(caGroup.getGroupUUID(), caGroup.getName());
    PermissionRule rule = PermissionRule.builder(groupRef).setAction(PermissionRule.Action.ALLOW).build();
    if (autoVerify) {
        ca = ContributorAgreement.builder("cla-test");
        ca.setAutoVerify(groupRef);
        ca.setAccepted(ImmutableList.of(rule));
    } else {
        ca = ContributorAgreement.builder("cla-test-no-auto-verify");
    }
    ca.setDescription("description");
    ca.setAgreementUrl("agreement-url");
    ca.setAccepted(ImmutableList.of(rule));
    ca.setExcludeProjectsRegexes(ImmutableList.of("ExcludedProject"));
    try (ProjectConfigUpdate u = updateProject(allProjects)) {
        ContributorAgreement contributorAgreement = ca.build();
        u.getConfig().replace(contributorAgreement);
        u.save();
        return contributorAgreement;
    }
}
Also used : GroupApi(com.google.gerrit.extensions.api.groups.GroupApi) AccountGroup(com.google.gerrit.entities.AccountGroup) PermissionRule(com.google.gerrit.entities.PermissionRule) ContributorAgreement(com.google.gerrit.entities.ContributorAgreement) GroupReference(com.google.gerrit.entities.GroupReference) InternalGroup(com.google.gerrit.entities.InternalGroup)

Example 13 with PermissionRule

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

the class GetAgreements method apply.

@Override
public Response<List<AgreementInfo>> apply(AccountResource resource) throws RestApiException, PermissionBackendException {
    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()) {
        try {
            permissionBackend.user(user).check(GlobalPermission.ADMINISTRATE_SERVER);
        } catch (AuthException e) {
            throw new AuthException("not allowed to get contributor agreements", e);
        }
    }
    List<AgreementInfo> results = new ArrayList<>();
    Collection<ContributorAgreement> cas = projectCache.getAllProjects().getConfig().getContributorAgreements().values();
    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 {
                    logger.atWarning().log("group \"%s\" does not exist, referenced in CLA \"%s\"", rule.getGroup().getName(), ca.getName());
                }
            }
        }
        if (user.getEffectiveGroups().containsAnyOf(groupIds)) {
            results.add(agreementJson.format(ca));
        }
    }
    return Response.ok(results);
}
Also used : MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) PermissionRule(com.google.gerrit.entities.PermissionRule) AgreementInfo(com.google.gerrit.extensions.common.AgreementInfo) ContributorAgreement(com.google.gerrit.entities.ContributorAgreement) ArrayList(java.util.ArrayList) AuthException(com.google.gerrit.extensions.restapi.AuthException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser)

Example 14 with PermissionRule

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

the class GetAccess method apply.

@Override
public Response<ProjectAccessInfo> apply(ProjectResource rsrc) throws ResourceNotFoundException, ResourceConflictException, IOException, PermissionBackendException {
    // Load the current configuration from the repository, ensuring it's the most
    // recent version available. If it differs from what was in the project
    // state, force a cache flush now.
    Project.NameKey projectName = rsrc.getNameKey();
    ProjectAccessInfo info = new ProjectAccessInfo();
    ProjectState projectState = projectCache.get(projectName).orElseThrow(illegalState(projectName));
    PermissionBackend.ForProject perm = permissionBackend.currentUser().project(projectName);
    ProjectConfig config;
    try (MetaDataUpdate md = metaDataUpdateFactory.get().create(projectName)) {
        config = projectConfigFactory.read(md);
        info.configWebLinks = new ArrayList<>();
        // config may have a null revision if the repo doesn't have its own refs/meta/config.
        if (config.getRevision() != null) {
            info.configWebLinks.addAll(webLinks.getFileHistoryLinks(projectName.get(), config.getRevision().getName(), ProjectConfig.PROJECT_CONFIG));
        }
        if (config.updateGroupNames(groupBackend)) {
            md.setMessage("Update group names\n");
            config.commit(md);
            projectCache.evictAndReindex(config.getProject());
            projectState = projectCache.get(projectName).orElseThrow(illegalState(projectName));
            perm = permissionBackend.currentUser().project(projectName);
        } else if (config.getRevision() != null && !config.getRevision().equals(projectState.getConfig().getRevision().orElse(null))) {
            projectCache.evictAndReindex(config.getProject());
            projectState = projectCache.get(projectName).orElseThrow(illegalState(projectName));
            perm = permissionBackend.currentUser().project(projectName);
        }
    } catch (ConfigInvalidException e) {
        throw new ResourceConflictException(e.getMessage());
    } catch (RepositoryNotFoundException e) {
        throw new ResourceNotFoundException(rsrc.getName(), e);
    }
    // The following implementation must match the ProjectAccessFactory JSON RPC endpoint.
    info.local = new HashMap<>();
    info.ownerOf = new HashSet<>();
    Map<AccountGroup.UUID, GroupInfo> groups = new HashMap<>();
    boolean canReadConfig = check(perm, RefNames.REFS_CONFIG, READ);
    boolean canWriteConfig = check(perm, ProjectPermission.WRITE_CONFIG);
    // config to set the project state to any state that is not HIDDEN.
    if (!canWriteConfig) {
        projectState.checkStatePermitsRead();
    }
    for (AccessSection section : config.getAccessSections()) {
        String name = section.getName();
        if (AccessSection.GLOBAL_CAPABILITIES.equals(name)) {
            if (canWriteConfig) {
                info.local.put(name, createAccessSection(groups, section));
                info.ownerOf.add(name);
            } else if (canReadConfig) {
                info.local.put(section.getName(), createAccessSection(groups, section));
            }
        } else if (AccessSection.isValidRefSectionName(name)) {
            if (check(perm, name, WRITE_CONFIG)) {
                info.local.put(name, createAccessSection(groups, section));
                info.ownerOf.add(name);
            } else if (canReadConfig) {
                info.local.put(name, createAccessSection(groups, section));
            } else if (check(perm, name, READ)) {
                // Filter the section to only add rules describing groups that
                // are visible to the current-user. This includes any group the
                // user is a member of, as well as groups they own or that
                // are visible to all users.
                AccessSection.Builder dst = null;
                for (Permission srcPerm : section.getPermissions()) {
                    Permission.Builder dstPerm = null;
                    for (PermissionRule srcRule : srcPerm.getRules()) {
                        AccountGroup.UUID groupId = srcRule.getGroup().getUUID();
                        if (groupId == null) {
                            continue;
                        }
                        loadGroup(groups, groupId);
                        if (dstPerm == null) {
                            if (dst == null) {
                                dst = AccessSection.builder(name);
                                info.local.put(name, createAccessSection(groups, dst.build()));
                            }
                            dstPerm = dst.upsertPermission(srcPerm.getName());
                        }
                        dstPerm.add(srcRule.toBuilder());
                    }
                }
            }
        }
    }
    if (info.ownerOf.isEmpty()) {
        try {
            permissionBackend.currentUser().check(GlobalPermission.ADMINISTRATE_SERVER);
            // Special case: If the section list is empty, this project has no current
            // access control information. Fall back to site administrators.
            info.ownerOf.add(AccessSection.ALL);
        } catch (AuthException e) {
        // Do nothing.
        }
    }
    if (config.getRevision() != null) {
        info.revision = config.getRevision().name();
    }
    ProjectState parent = Iterables.getFirst(projectState.parents(), null);
    if (parent != null) {
        info.inheritsFrom = projectJson.format(parent.getProject());
    }
    if (projectName.equals(allProjectsName) && permissionBackend.currentUser().testOrFalse(ADMINISTRATE_SERVER)) {
        info.ownerOf.add(AccessSection.GLOBAL_CAPABILITIES);
    }
    info.isOwner = toBoolean(canWriteConfig);
    info.canUpload = toBoolean(projectState.statePermitsWrite() && (canWriteConfig || (canReadConfig && perm.ref(RefNames.REFS_CONFIG).testOrFalse(CREATE_CHANGE))));
    info.canAdd = toBoolean(perm.testOrFalse(CREATE_REF));
    info.canAddTags = toBoolean(perm.testOrFalse(CREATE_TAG_REF));
    info.configVisible = canReadConfig || canWriteConfig;
    info.groups = groups.entrySet().stream().filter(e -> e.getValue() != null).collect(toMap(e -> e.getKey().get(), Map.Entry::getValue));
    return Response.ok(info);
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) HashMap(java.util.HashMap) PermissionRule(com.google.gerrit.entities.PermissionRule) ProjectAccessInfo(com.google.gerrit.extensions.api.access.ProjectAccessInfo) AuthException(com.google.gerrit.extensions.restapi.AuthException) RefPermission(com.google.gerrit.server.permissions.RefPermission) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) ProjectPermission(com.google.gerrit.server.permissions.ProjectPermission) Permission(com.google.gerrit.entities.Permission) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) GroupInfo(com.google.gerrit.extensions.common.GroupInfo) RepositoryNotFoundException(org.eclipse.jgit.errors.RepositoryNotFoundException) AccessSection(com.google.gerrit.entities.AccessSection) ProjectConfig(com.google.gerrit.server.project.ProjectConfig) Project(com.google.gerrit.entities.Project) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) ProjectState(com.google.gerrit.server.project.ProjectState) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate)

Example 15 with PermissionRule

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

the class GetAccess method createAccessSection.

private AccessSectionInfo createAccessSection(Map<AccountGroup.UUID, GroupInfo> groups, AccessSection section) {
    AccessSectionInfo accessSectionInfo = new AccessSectionInfo();
    accessSectionInfo.permissions = new HashMap<>();
    for (Permission p : section.getPermissions()) {
        PermissionInfo pInfo = new PermissionInfo(p.getLabel(), p.getExclusiveGroup() ? true : null);
        pInfo.rules = new HashMap<>();
        for (PermissionRule r : p.getRules()) {
            PermissionRuleInfo info = new PermissionRuleInfo(ACTION_TYPE.get(r.getAction()), r.getForce());
            if (r.hasRange()) {
                info.max = r.getMax();
                info.min = r.getMin();
            }
            AccountGroup.UUID group = r.getGroup().getUUID();
            if (group != null) {
                // First entry for the group wins
                pInfo.rules.putIfAbsent(group.get(), info);
                loadGroup(groups, group);
            }
        }
        accessSectionInfo.permissions.put(p.getName(), pInfo);
    }
    return accessSectionInfo;
}
Also used : PermissionInfo(com.google.gerrit.extensions.api.access.PermissionInfo) AccountGroup(com.google.gerrit.entities.AccountGroup) PermissionRule(com.google.gerrit.entities.PermissionRule) RefPermission(com.google.gerrit.server.permissions.RefPermission) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) ProjectPermission(com.google.gerrit.server.permissions.ProjectPermission) Permission(com.google.gerrit.entities.Permission) PermissionRuleInfo(com.google.gerrit.extensions.api.access.PermissionRuleInfo) AccessSectionInfo(com.google.gerrit.extensions.api.access.AccessSectionInfo)

Aggregations

PermissionRule (com.google.gerrit.entities.PermissionRule)18 Permission (com.google.gerrit.entities.Permission)7 ArrayList (java.util.ArrayList)6 AccessSection (com.google.gerrit.entities.AccessSection)5 ContributorAgreement (com.google.gerrit.entities.ContributorAgreement)4 GroupReference (com.google.gerrit.entities.GroupReference)3 AuthException (com.google.gerrit.extensions.restapi.AuthException)3 HashSet (java.util.HashSet)3 ImmutableList (com.google.common.collect.ImmutableList)2 AccountGroup (com.google.gerrit.entities.AccountGroup)2 PermissionRange (com.google.gerrit.entities.PermissionRange)2 IdentifiedUser (com.google.gerrit.server.IdentifiedUser)2 MetaDataUpdate (com.google.gerrit.server.git.meta.MetaDataUpdate)2 GlobalPermission (com.google.gerrit.server.permissions.GlobalPermission)2 ProjectPermission (com.google.gerrit.server.permissions.ProjectPermission)2 RefPermission (com.google.gerrit.server.permissions.RefPermission)2 ProjectConfig (com.google.gerrit.server.project.ProjectConfig)2 ProjectState (com.google.gerrit.server.project.ProjectState)2 IOException (java.io.IOException)2 List (java.util.List)2