Search in sources :

Example 1 with Permission

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

the class CreateGroupPermissionSyncer method syncIfNeeded.

/**
 * Checks if {@code GlobalCapability.CREATE_GROUP} and {@code CREATE} permission on {@code
 * refs/groups/*} have diverged and syncs them by applying the {@code CREATE} permission to {@code
 * refs/groups/*}.
 */
public void syncIfNeeded() throws IOException, ConfigInvalidException {
    ProjectState allProjectsState = projectCache.getAllProjects();
    ProjectState allUsersState = projectCache.getAllUsers();
    Set<PermissionRule> createGroupsGlobal = new HashSet<>(allProjectsState.getCapabilityCollection().createGroup);
    Set<PermissionRule> createGroupsRef = new HashSet<>();
    Optional<AccessSection> allUsersCreateGroupAccessSection = allUsersState.getConfig().getAccessSection(RefNames.REFS_GROUPS + "*");
    if (allUsersCreateGroupAccessSection.isPresent()) {
        Permission create = allUsersCreateGroupAccessSection.get().getPermission(Permission.CREATE);
        if (create != null && create.getRules() != null) {
            createGroupsRef.addAll(create.getRules());
        }
    }
    if (Sets.symmetricDifference(createGroupsGlobal, createGroupsRef).isEmpty()) {
        // Nothing to sync
        return;
    }
    try (MetaDataUpdate md = metaDataUpdateFactory.get().create(allUsers)) {
        ProjectConfig config = projectConfigFactory.read(md);
        config.upsertAccessSection(RefNames.REFS_GROUPS + "*", refsGroupsAccessSectionBuilder -> {
            if (createGroupsGlobal.isEmpty()) {
                refsGroupsAccessSectionBuilder.modifyPermissions(permissions -> {
                    permissions.removeIf(p -> Permission.CREATE.equals(p.getName()));
                });
            } else {
                // The create permission is managed by Gerrit at this point only so there is no
                // concern of overwriting user-defined permissions here.
                Permission.Builder createGroupPermission = Permission.builder(Permission.CREATE);
                refsGroupsAccessSectionBuilder.remove(createGroupPermission);
                refsGroupsAccessSectionBuilder.addPermission(createGroupPermission);
                createGroupsGlobal.stream().map(p -> p.toBuilder()).forEach(createGroupPermission::add);
            }
        });
        config.commit(md);
        projectCache.evictAndReindex(config.getProject());
    }
}
Also used : ProjectConfig(com.google.gerrit.server.project.ProjectConfig) AllUsersName(com.google.gerrit.server.config.AllUsersName) ProjectConfig(com.google.gerrit.server.project.ProjectConfig) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ProjectCache(com.google.gerrit.server.project.ProjectCache) AccessSection(com.google.gerrit.entities.AccessSection) Inject(com.google.inject.Inject) Permission(com.google.gerrit.entities.Permission) ProjectState(com.google.gerrit.server.project.ProjectState) Set(java.util.Set) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) ChangeMergedListener(com.google.gerrit.extensions.events.ChangeMergedListener) HashSet(java.util.HashSet) Provider(com.google.inject.Provider) AllProjectsName(com.google.gerrit.server.config.AllProjectsName) PermissionRule(com.google.gerrit.entities.PermissionRule) RefNames(com.google.gerrit.entities.RefNames) Optional(java.util.Optional) FluentLogger(com.google.common.flogger.FluentLogger) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate) Singleton(com.google.inject.Singleton) PermissionRule(com.google.gerrit.entities.PermissionRule) Permission(com.google.gerrit.entities.Permission) ProjectState(com.google.gerrit.server.project.ProjectState) AccessSection(com.google.gerrit.entities.AccessSection) HashSet(java.util.HashSet) MetaDataUpdate(com.google.gerrit.server.git.meta.MetaDataUpdate)

Example 2 with Permission

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

the class AccountManager method create.

private AuthResult create(AuthRequest who) throws AccountException, IOException, ConfigInvalidException {
    Account.Id newId = Account.id(sequences.nextAccountId());
    logger.atFine().log("Assigning new Id %s to account", newId);
    ExternalId extId = externalIdFactory.createWithEmail(who.getExternalIdKey(), newId, who.getEmailAddress());
    logger.atFine().log("Created external Id: %s", extId);
    checkEmailNotUsed(newId, extId);
    ExternalId userNameExtId = who.getUserName().isPresent() ? createUsername(newId, who.getUserName().get()) : null;
    boolean isFirstAccount = awaitsFirstAccountCheck.getAndSet(false) && !accounts.hasAnyAccount();
    AccountState accountState;
    try {
        accountState = accountsUpdateProvider.get().insert("Create Account on First Login", newId, u -> {
            u.setFullName(who.getDisplayName()).setPreferredEmail(extId.email()).addExternalId(extId);
            if (userNameExtId != null) {
                u.addExternalId(userNameExtId);
            }
        });
    } catch (DuplicateExternalIdKeyException e) {
        throw new AccountException("Cannot assign external ID \"" + e.getDuplicateKey().get() + "\" to account " + newId + "; external ID already in use.");
    } finally {
        // If adding the account failed, it may be that it actually was the
        // first account. So we reset the 'check for first account'-guard, as
        // otherwise the first account would not get administration permissions.
        awaitsFirstAccountCheck.set(isFirstAccount);
    }
    if (userNameExtId != null) {
        who.getUserName().ifPresent(sshKeyCache::evict);
    }
    IdentifiedUser user = userFactory.create(newId);
    if (isFirstAccount) {
        // This is the first user account on our site. Assume this user
        // is going to be the site's administrator and just make them that
        // to bootstrap the authentication database.
        // 
        Permission admin = projectCache.getAllProjects().getConfig().getAccessSection(AccessSection.GLOBAL_CAPABILITIES).orElseThrow(() -> new IllegalStateException("access section does not exist")).getPermission(GlobalCapability.ADMINISTRATE_SERVER);
        AccountGroup.UUID adminGroupUuid = admin.getRules().get(0).getGroup().getUUID();
        addGroupMember(adminGroupUuid, user);
    }
    realm.onCreateAccount(who, accountState.account());
    return new AuthResult(newId, extId.key(), true);
}
Also used : ExternalIdKeyFactory(com.google.gerrit.server.account.externalids.ExternalIdKeyFactory) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) GlobalCapability(com.google.gerrit.common.data.GlobalCapability) ProjectCache(com.google.gerrit.server.project.ProjectCache) Inject(com.google.inject.Inject) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) ArrayList(java.util.ArrayList) GroupsUpdate(com.google.gerrit.server.group.db.GroupsUpdate) Strings(com.google.common.base.Strings) Config(org.eclipse.jgit.lib.Config) Preconditions.checkArgument(com.google.common.base.Preconditions.checkArgument) ImmutableList(com.google.common.collect.ImmutableList) SCHEME_USERNAME(com.google.gerrit.server.account.externalids.ExternalId.SCHEME_USERNAME) ExternalIdFactory(com.google.gerrit.server.account.externalids.ExternalIdFactory) ImmutableSet.toImmutableSet(com.google.common.collect.ImmutableSet.toImmutableSet) NoSuchUserException(com.google.gerrit.server.auth.NoSuchUserException) AccountGroup(com.google.gerrit.entities.AccountGroup) ImmutableSet(com.google.common.collect.ImmutableSet) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) Sequences(com.google.gerrit.server.notedb.Sequences) SshKeyCache(com.google.gerrit.server.ssh.SshKeyCache) AccessSection(com.google.gerrit.entities.AccessSection) StorageException(com.google.gerrit.exceptions.StorageException) Collection(java.util.Collection) Permission(com.google.gerrit.entities.Permission) Account(com.google.gerrit.entities.Account) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) Sets(com.google.common.collect.Sets) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Objects(java.util.Objects) Consumer(java.util.function.Consumer) Provider(com.google.inject.Provider) List(java.util.List) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ServerInitiated(com.google.gerrit.server.ServerInitiated) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) VisibleForTesting(com.google.common.annotations.VisibleForTesting) DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) GroupDelta(com.google.gerrit.server.group.db.GroupDelta) FluentLogger(com.google.common.flogger.FluentLogger) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) DuplicateExternalIdKeyException(com.google.gerrit.server.account.externalids.DuplicateExternalIdKeyException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) AccountGroup(com.google.gerrit.entities.AccountGroup) Permission(com.google.gerrit.entities.Permission)

Example 3 with Permission

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

the class PermissionCollection method calculateAllowRules.

/**
 * calculates permissions for ALLOW processing.
 */
private List<PermissionRule> calculateAllowRules(String permName) {
    Set<SeenRule> seen = new HashSet<>();
    List<PermissionRule> r = new ArrayList<>();
    for (AccessSection s : accessSectionsUpward) {
        Permission p = s.getPermission(permName);
        if (p == null) {
            continue;
        }
        for (PermissionRule pr : p.getRules()) {
            SeenRule sr = SeenRule.create(s, pr);
            if (seen.contains(sr)) {
                // negating access.
                continue;
            }
            seen.add(sr);
            if (pr.getAction() == BLOCK) {
                // Block rules are handled elsewhere.
                continue;
            }
            if (pr.getAction() == PermissionRule.Action.DENY) {
                // DENY rules work by not adding ALLOW rules. Nothing else to do.
                continue;
            }
            r.add(pr);
        }
        if (p.getExclusiveGroup()) {
            // We found an exclusive permission, so no need to further go up the hierarchy.
            break;
        }
    }
    return r;
}
Also used : PermissionRule(com.google.gerrit.entities.PermissionRule) ArrayList(java.util.ArrayList) Permission(com.google.gerrit.entities.Permission) AccessSection(com.google.gerrit.entities.AccessSection) HashSet(java.util.HashSet)

Example 4 with Permission

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

the class PermissionCollection method calculateBlockRules.

// Calculates the inputs for determining BLOCK status, grouped by project.
private List<List<Permission>> calculateBlockRules(String permName) {
    List<List<Permission>> result = new ArrayList<>();
    for (List<AccessSection> secs : this.accessSectionsPerProjectDownward) {
        List<Permission> perms = new ArrayList<>();
        boolean blockFound = false;
        for (AccessSection sec : secs) {
            Permission p = sec.getPermission(permName);
            if (p == null) {
                continue;
            }
            for (PermissionRule pr : p.getRules()) {
                if (blockFound || pr.getAction() == Action.BLOCK) {
                    blockFound = true;
                    break;
                }
            }
            perms.add(p);
        }
        if (blockFound) {
            result.add(perms);
        }
    }
    return result;
}
Also used : PermissionRule(com.google.gerrit.entities.PermissionRule) ArrayList(java.util.ArrayList) Permission(com.google.gerrit.entities.Permission) ArrayList(java.util.ArrayList) Collectors.toList(java.util.stream.Collectors.toList) List(java.util.List) AccessSection(com.google.gerrit.entities.AccessSection)

Example 5 with Permission

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

the class ProjectControl method allRefPatterns.

private Set<String> allRefPatterns(String permissionName) {
    Set<String> all = new HashSet<>();
    for (SectionMatcher matcher : access()) {
        AccessSection section = matcher.getSection();
        Permission permission = section.getPermission(permissionName);
        if (permission != null) {
            all.add(section.getName());
        }
    }
    return all;
}
Also used : Permission(com.google.gerrit.entities.Permission) CoreOrPluginProjectPermission(com.google.gerrit.extensions.api.access.CoreOrPluginProjectPermission) PluginProjectPermission(com.google.gerrit.extensions.api.access.PluginProjectPermission) SectionMatcher(com.google.gerrit.server.project.SectionMatcher) AccessSection(com.google.gerrit.entities.AccessSection) HashSet(java.util.HashSet)

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