Search in sources :

Example 6 with Permission

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

the class ProjectConfigTest method readConfig.

@Test
public void readConfig() throws Exception {
    RevCommit rev = tr.commit().add("groups", group(developers)).add("project.config", "[access \"refs/heads/*\"]\n" + "  exclusiveGroupPermissions = read submit create\n" + "  submit = group Developers\n" + "  push = group Developers\n" + "  read = group Developers\n" + "[accounts]\n" + "  sameGroupVisibility = deny group Developers\n" + "  sameGroupVisibility = block group Staff\n" + "[contributor-agreement \"Individual\"]\n" + "  description = A simple description\n" + "  matchProjects = ^/ourproject\n" + "  matchProjects = ^/ourotherproject\n" + "  matchProjects = ^/someotherroot/ourproject\n" + "  excludeProjects = ^/theirproject\n" + "  excludeProjects = ^/theirotherproject\n" + "  excludeProjects = ^/someotherroot/theirproject\n" + "  excludeProjects = ^/someotherroot/theirotherproject\n" + "  accepted = group Developers\n" + "  accepted = group Staff\n" + "  autoVerify = group Developers\n" + "  agreementUrl = http://www.example.com/agree\n").create();
    ProjectConfig cfg = read(rev);
    assertThat(cfg.getAccountsSection().getSameGroupVisibility()).hasSize(2);
    ContributorAgreement ca = cfg.getContributorAgreement("Individual");
    assertThat(ca.getName()).isEqualTo("Individual");
    assertThat(ca.getDescription()).isEqualTo("A simple description");
    assertThat(ca.getMatchProjectsRegexes()).containsExactly("^/ourproject", "^/ourotherproject", "^/someotherroot/ourproject");
    assertThat(ca.getExcludeProjectsRegexes()).containsExactly("^/theirproject", "^/theirotherproject", "^/someotherroot/theirproject", "^/someotherroot/theirotherproject");
    assertThat(ca.getAgreementUrl()).isEqualTo("http://www.example.com/agree");
    assertThat(ca.getAccepted()).hasSize(2);
    assertThat(ca.getAccepted().get(0).getGroup()).isEqualTo(developers);
    assertThat(ca.getAccepted().get(1).getGroup().getName()).isEqualTo("Staff");
    assertThat(ca.getAutoVerify().getName()).isEqualTo("Developers");
    AccessSection section = cfg.getAccessSection("refs/heads/*");
    assertThat(section).isNotNull();
    assertThat(cfg.getAccessSection("refs/*")).isNull();
    Permission create = section.getPermission(Permission.CREATE);
    Permission submit = section.getPermission(Permission.SUBMIT);
    Permission read = section.getPermission(Permission.READ);
    Permission push = section.getPermission(Permission.PUSH);
    assertThat(create.getExclusiveGroup()).isTrue();
    assertThat(submit.getExclusiveGroup()).isTrue();
    assertThat(read.getExclusiveGroup()).isTrue();
    assertThat(push.getExclusiveGroup()).isFalse();
}
Also used : ContributorAgreement(com.google.gerrit.entities.ContributorAgreement) Permission(com.google.gerrit.entities.Permission) AccessSection(com.google.gerrit.entities.AccessSection) RevCommit(org.eclipse.jgit.revwalk.RevCommit) Test(org.junit.Test)

Example 7 with Permission

use of com.google.gerrit.entities.Permission 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 8 with Permission

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

the class ProjectConfig method getCacheable.

/**
 * Returns an immutable, thread-safe representation of this object that can be cached.
 */
public CachedProjectConfig getCacheable() {
    CachedProjectConfig.Builder builder = CachedProjectConfig.builder().setProject(project).setAccountsSection(accountsSection).setBranchOrderSection(Optional.ofNullable(branchOrderSection)).setMimeTypes(mimeTypes).setRulesId(Optional.ofNullable(rulesId)).setRevision(Optional.ofNullable(getRevision())).setMaxObjectSizeLimit(maxObjectSizeLimit).setCheckReceivedObjects(checkReceivedObjects).setExtensionPanelSections(extensionPanelSections);
    groupList.byUUID().values().forEach(g -> builder.addGroup(g));
    contributorAgreements.values().forEach(c -> builder.addContributorAgreement(c));
    notifySections.values().forEach(n -> builder.addNotifySection(n));
    subscribeSections.values().forEach(s -> builder.addSubscribeSection(s));
    commentLinkSections.values().forEach(c -> builder.addCommentLinkSection(c));
    labelSections.values().forEach(l -> builder.addLabelSection(l));
    submitRequirementSections.values().forEach(sr -> builder.addSubmitRequirementSection(sr));
    pluginConfigs.entrySet().forEach(c -> builder.addPluginConfig(c.getKey(), c.getValue().toText()));
    projectLevelConfigs.entrySet().forEach(c -> builder.addProjectLevelConfig(c.getKey(), c.getValue().toText()));
    if (projectName.equals(allProjectsName)) {
        // Filter out permissions that aren't allowed to be set on All-Projects
        accessSections.values().forEach(a -> {
            List<Permission.Builder> copy = new ArrayList<>();
            for (Permission p : a.getPermissions()) {
                if (Permission.canBeOnAllProjects(a.getName(), p.getName())) {
                    copy.add(p.toBuilder());
                }
            }
            AccessSection section = AccessSection.builder(a.getName()).modifyPermissions(permissions -> permissions.addAll(copy)).build();
            builder.addAccessSection(section);
        });
    } else {
        accessSections.values().forEach(a -> builder.addAccessSection(a));
    }
    return builder.build();
}
Also used : GroupBackend(com.google.gerrit.server.account.GroupBackend) Arrays(java.util.Arrays) GlobalCapability(com.google.gerrit.common.data.GlobalCapability) Inject(com.google.inject.Inject) RevWalk(org.eclipse.jgit.revwalk.RevWalk) InheritableBoolean(com.google.gerrit.extensions.client.InheritableBoolean) Config(org.eclipse.jgit.lib.Config) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) VersionedMetaData(com.google.gerrit.server.git.meta.VersionedMetaData) LabelValue(com.google.gerrit.entities.LabelValue) LabelType(com.google.gerrit.entities.LabelType) ConfigUtil(com.google.gerrit.server.config.ConfigUtil) Locale(java.util.Locale) Map(java.util.Map) ContributorAgreement(com.google.gerrit.entities.ContributorAgreement) RefNames(com.google.gerrit.entities.RefNames) Splitter(com.google.common.base.Splitter) PluginConfig(com.google.gerrit.server.config.PluginConfig) EnumSet(java.util.EnumSet) Permission.isPermission(com.google.gerrit.entities.Permission.isPermission) ImmutableSet(com.google.common.collect.ImmutableSet) PatternSyntaxException(java.util.regex.PatternSyntaxException) ImmutableList.toImmutableList(com.google.common.collect.ImmutableList.toImmutableList) AccessSection(com.google.gerrit.entities.AccessSection) Collection(java.util.Collection) Set(java.util.Set) Sets(com.google.common.collect.Sets) Preconditions.checkState(com.google.common.base.Preconditions.checkState) GroupReference(com.google.gerrit.entities.GroupReference) Objects(java.util.Objects) List(java.util.List) Nullable(com.google.gerrit.common.Nullable) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) DEFAULT_SUBMIT_TYPE(com.google.gerrit.entities.Project.DEFAULT_SUBMIT_TYPE) ConfiguredMimeTypes(com.google.gerrit.entities.ConfiguredMimeTypes) NotifyConfig(com.google.gerrit.entities.NotifyConfig) BooleanProjectConfig(com.google.gerrit.entities.BooleanProjectConfig) Optional(java.util.Optional) Pattern(java.util.regex.Pattern) AllProjectsConfigProvider(com.google.gerrit.server.config.AllProjectsConfigProvider) FluentLogger(com.google.common.flogger.FluentLogger) Joiner(com.google.common.base.Joiner) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate) Singleton(com.google.inject.Singleton) ValidationError(com.google.gerrit.server.git.ValidationError) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Shorts(com.google.common.primitives.Shorts) SubmitRequirementExpression(com.google.gerrit.entities.SubmitRequirementExpression) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) LinkedHashMap(java.util.LinkedHashMap) Strings(com.google.common.base.Strings) PluginPermissionsUtil.isValidPluginPermission(com.google.gerrit.server.permissions.PluginPermissionsUtil.isValidPluginPermission) ImmutableList(com.google.common.collect.ImmutableList) GroupDescription(com.google.gerrit.entities.GroupDescription) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) Objects.requireNonNull(java.util.Objects.requireNonNull) LabelFunction(com.google.gerrit.entities.LabelFunction) PermissionRule(com.google.gerrit.entities.PermissionRule) CachedProjectConfig(com.google.gerrit.entities.CachedProjectConfig) UsedAt(com.google.gerrit.common.UsedAt) Address(com.google.gerrit.entities.Address) SubmitRequirement(com.google.gerrit.entities.SubmitRequirement) AccountGroup(com.google.gerrit.entities.AccountGroup) AccountsSection(com.google.gerrit.entities.AccountsSection) CharMatcher(com.google.common.base.CharMatcher) Permission(com.google.gerrit.entities.Permission) IOException(java.io.IOException) ProjectState(com.google.gerrit.extensions.client.ProjectState) Maps(com.google.common.collect.Maps) ObjectId(org.eclipse.jgit.lib.ObjectId) Consumer(java.util.function.Consumer) Collectors.toList(java.util.stream.Collectors.toList) NotifyType(com.google.gerrit.entities.NotifyConfig.NotifyType) SubscribeSection(com.google.gerrit.entities.SubscribeSection) Project(com.google.gerrit.entities.Project) StoredConfig(org.eclipse.jgit.lib.StoredConfig) VisibleForTesting(com.google.common.annotations.VisibleForTesting) StoredCommentLinkInfo(com.google.gerrit.entities.StoredCommentLinkInfo) BranchOrderSection(com.google.gerrit.entities.BranchOrderSection) Collections(java.util.Collections) Action(com.google.gerrit.entities.PermissionRule.Action) Repository(org.eclipse.jgit.lib.Repository) InvalidNameException(com.google.gerrit.exceptions.InvalidNameException) CommitBuilder(org.eclipse.jgit.lib.CommitBuilder) ArrayList(java.util.ArrayList) Permission.isPermission(com.google.gerrit.entities.Permission.isPermission) PluginPermissionsUtil.isValidPluginPermission(com.google.gerrit.server.permissions.PluginPermissionsUtil.isValidPluginPermission) Permission(com.google.gerrit.entities.Permission) CachedProjectConfig(com.google.gerrit.entities.CachedProjectConfig) AccessSection(com.google.gerrit.entities.AccessSection)

Example 9 with Permission

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

the class SetAccessUtil method validateChanges.

/**
 * Checks that the removals and additions are logically valid, but doesn't check current user's
 * permission.
 */
void validateChanges(ProjectConfig config, List<AccessSection> removals, List<AccessSection> additions) throws BadRequestException, InvalidNameException {
    // Perform permission checks
    for (AccessSection section : Iterables.concat(additions, removals)) {
        boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(section.getName());
        if (isGlobalCapabilities) {
            if (!allProjects.equals(config.getName())) {
                throw new BadRequestException("Cannot edit global capabilities for projects other than " + allProjects.get());
            }
        }
    }
    // Perform addition checks
    for (AccessSection section : additions) {
        String name = section.getName();
        boolean isGlobalCapabilities = AccessSection.GLOBAL_CAPABILITIES.equals(name);
        if (!isGlobalCapabilities) {
            if (!AccessSection.isValidRefSectionName(name)) {
                throw new BadRequestException("invalid section name");
            }
            RefPattern.validate(name);
            // Check all permissions for soundness
            for (Permission p : section.getPermissions()) {
                if (!isPermission(p.getName())) {
                    throw new BadRequestException("Unknown permission: " + p.getName());
                }
            }
        } else {
            // Check all permissions for soundness
            for (Permission p : section.getPermissions()) {
                if (!isCapability(p.getName())) {
                    throw new BadRequestException("Unknown global capability: " + p.getName());
                }
            }
        }
    }
}
Also used : Permission(com.google.gerrit.entities.Permission) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) AccessSection(com.google.gerrit.entities.AccessSection)

Example 10 with Permission

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

the class GrantRevertPermission method execute.

public void execute(Project.NameKey projectName) throws IOException, ConfigInvalidException {
    GroupReference registeredUsers = systemGroupBackend.getGroup(REGISTERED_USERS);
    try (Repository repo = repoManager.openRepository(projectName)) {
        MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, projectName, repo);
        ProjectConfig projectConfig = projectConfigFactory.read(md);
        AtomicBoolean shouldExit = new AtomicBoolean(false);
        projectConfig.upsertAccessSection(AccessSection.HEADS, heads -> {
            Permission permissionOnRefsHeads = heads.build().getPermission(Permission.REVERT);
            if (permissionOnRefsHeads != null) {
                if (permissionOnRefsHeads.getRule(registeredUsers) == null || permissionOnRefsHeads.getRules().size() > 1) {
                    // If admins already changed the permission, don't do anything.
                    shouldExit.set(true);
                    return;
                }
                // permission already exists in refs/heads/*, delete it for Registered Users.
                remove(projectConfig, heads, Permission.REVERT, registeredUsers);
            }
        });
        if (shouldExit.get()) {
            return;
        }
        projectConfig.upsertAccessSection(AccessSection.ALL, all -> {
            Permission permissionOnRefsStar = all.build().getPermission(Permission.REVERT);
            if (permissionOnRefsStar != null && permissionOnRefsStar.getRule(registeredUsers) != null) {
                // permission already exists in refs/*, don't do anything.
                return;
            }
            // If the permission doesn't exist of refs/* for Registered Users, grant it.
            grant(projectConfig, all, Permission.REVERT, registeredUsers);
        });
        md.getCommitBuilder().setAuthor(serverUser);
        md.getCommitBuilder().setCommitter(serverUser);
        md.setMessage("Add revert permission for all registered users\n");
        projectConfig.commit(md);
    }
}
Also used : ProjectConfig(com.google.gerrit.server.project.ProjectConfig) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Repository(org.eclipse.jgit.lib.Repository) Permission(com.google.gerrit.entities.Permission) GroupReference(com.google.gerrit.entities.GroupReference) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate)

Aggregations

Permission (com.google.gerrit.entities.Permission)21 AccessSection (com.google.gerrit.entities.AccessSection)16 PermissionRule (com.google.gerrit.entities.PermissionRule)9 MetaDataUpdate (com.google.gerrit.server.git.meta.MetaDataUpdate)5 ArrayList (java.util.ArrayList)5 HashSet (java.util.HashSet)5 ProjectConfig (com.google.gerrit.server.project.ProjectConfig)4 List (java.util.List)4 ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)4 ImmutableList (com.google.common.collect.ImmutableList)3 Sets (com.google.common.collect.Sets)3 FluentLogger (com.google.common.flogger.FluentLogger)3 AccountGroup (com.google.gerrit.entities.AccountGroup)3 GroupReference (com.google.gerrit.entities.GroupReference)3 CoreOrPluginProjectPermission (com.google.gerrit.extensions.api.access.CoreOrPluginProjectPermission)3 PluginProjectPermission (com.google.gerrit.extensions.api.access.PluginProjectPermission)3 Repository (org.eclipse.jgit.lib.Repository)3 Test (org.junit.Test)3 VisibleForTesting (com.google.common.annotations.VisibleForTesting)2 Preconditions.checkArgument (com.google.common.base.Preconditions.checkArgument)2