Search in sources :

Example 36 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class OAuthSessionOverOpenID method authenticateAndRedirect.

private void authenticateAndRedirect(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
    com.google.gerrit.server.account.AuthRequest areq = authRequestFactory.create(externalIdKeyFactory.parse(user.getExternalId()));
    AuthResult arsp;
    try {
        String claimedIdentifier = user.getClaimedIdentity();
        Optional<Account.Id> actualId = accountManager.lookup(user.getExternalId());
        Optional<Account.Id> claimedId = Optional.empty();
        // That why we query it here, not to lose linking mode.
        if (!Strings.isNullOrEmpty(claimedIdentifier)) {
            claimedId = accountManager.lookup(claimedIdentifier);
            if (!claimedId.isPresent()) {
                logger.atFine().log("Claimed identity is unknown");
            }
        }
        // and user account exists for this identity
        if (claimedId.isPresent()) {
            logger.atFine().log("Claimed identity is set and is known");
            if (actualId.isPresent()) {
                if (claimedId.get().equals(actualId.get())) {
                    // Both link to the same account, that's what we expected.
                    logger.atFine().log("Both link to the same account. All is fine.");
                } else {
                    // This is (for now) a fatal error. There are two records
                    // for what might be the same user. The admin would have to
                    // link the accounts manually.
                    logger.atFine().log("OAuth accounts disagree over user identity:\n" + "  Claimed ID: %s is %s\n" + "  Delgate ID: %s is %s", claimedId.get(), claimedIdentifier, actualId.get(), user.getExternalId());
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            } else {
                // Claimed account already exists: link to it.
                logger.atFine().log("Claimed account already exists: link to it.");
                try {
                    accountManager.link(claimedId.get(), areq);
                } catch (ConfigInvalidException e) {
                    logger.atSevere().log("Cannot link: %s to user identity:\n  Claimed ID: %s is %s", user.getExternalId(), claimedId.get(), claimedIdentifier);
                    rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                    return;
                }
            }
        } else if (linkMode) {
            // Use case 2: link mode activated from the UI
            Account.Id accountId = identifiedUser.get().getAccountId();
            try {
                logger.atFine().log("Linking \"%s\" to \"%s\"", user.getExternalId(), accountId);
                accountManager.link(accountId, areq);
            } catch (ConfigInvalidException e) {
                logger.atSevere().log("Cannot link: %s to user identity: %s", user.getExternalId(), accountId);
                rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
                return;
            } finally {
                linkMode = false;
            }
        }
        areq.setUserName(user.getUserName());
        areq.setEmailAddress(user.getEmailAddress());
        areq.setDisplayName(user.getDisplayName());
        arsp = accountManager.authenticate(areq);
    } catch (AccountException e) {
        logger.atSevere().withCause(e).log("Unable to authenticate user \"%s\"", user);
        rsp.sendError(HttpServletResponse.SC_FORBIDDEN);
        return;
    }
    webSession.get().login(arsp, true);
    StringBuilder rdr = new StringBuilder(urlProvider.get(req));
    rdr.append(Url.decode(redirectToken));
    rsp.sendRedirect(rdr.toString());
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) AccountException(com.google.gerrit.server.account.AccountException) AuthRequest(com.google.gerrit.server.account.AuthRequest) AuthResult(com.google.gerrit.server.account.AuthResult)

Example 37 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException 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 38 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class InitJGitConfig method run.

@Override
public void run() {
    ui.header("JGit Configuration");
    FileBasedConfig jgitConfig = new FileBasedConfig(sitePaths.jgit_config.toFile(), FS.DETECTED);
    try {
        jgitConfig.load();
        if (!jgitConfig.getNames(ConfigConstants.CONFIG_RECEIVE_SECTION).contains(ConfigConstants.CONFIG_KEY_AUTOGC)) {
            jgitConfig.setBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION, null, ConfigConstants.CONFIG_KEY_AUTOGC, false);
            jgitConfig.save();
            ui.error("Auto-configured \"receive.autogc = false\" to disable auto-gc after" + " git-receive-pack.");
        } else if (jgitConfig.getBoolean(ConfigConstants.CONFIG_RECEIVE_SECTION, ConfigConstants.CONFIG_KEY_AUTOGC, true)) {
            ui.error("WARNING: JGit option \"receive.autogc = true\". This is not recommended in Gerrit.\n" + "git-receive-pack will run auto gc after receiving data from " + "git-push and updating refs.\n" + "Disable this behavior to avoid the additional load it creates: " + "gc should be configured in gc config section or run as a separate process.");
        }
        if (jgitConfig.getNames(ConfigConstants.CONFIG_PROTOCOL_SECTION).contains(ConfigConstants.CONFIG_KEY_VERSION)) {
            String version = jgitConfig.getString(ConfigConstants.CONFIG_PROTOCOL_SECTION, null, ConfigConstants.CONFIG_KEY_VERSION);
            if (!TransferConfig.ProtocolVersion.V2.version().equals(version)) {
                ui.error("HINT: JGit option \"%s.%s = %s\". It's recommended to activate git\n" + "wire protocol version 2 to improve git fetch performance.", ConfigConstants.CONFIG_PROTOCOL_SECTION, ConfigConstants.CONFIG_KEY_VERSION, version);
            }
        }
    } catch (IOException e) {
        throw die(String.format("Handling JGit configuration %s failed", sitePaths.jgit_config), e);
    } catch (ConfigInvalidException e) {
        throw die(String.format("Invalid JGit configuration %s", sitePaths.jgit_config), e);
    }
}
Also used : ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) FileBasedConfig(org.eclipse.jgit.storage.file.FileBasedConfig)

Example 39 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException 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 40 with ConfigInvalidException

use of org.eclipse.jgit.errors.ConfigInvalidException in project gerrit by GerritCodeReview.

the class AccountIdHandler method parseArguments.

@Override
public int parseArguments(Parameters params) throws CmdLineException {
    String token = params.getParameter(0);
    Account.Id accountId;
    try {
        try {
            accountId = accountResolver.resolve(token).asUnique().account().id();
        } catch (UnprocessableEntityException e) {
            switch(authType) {
                case HTTP_LDAP:
                case CLIENT_SSL_CERT_LDAP:
                case LDAP:
                    accountId = createAccountByLdap(token);
                    break;
                case CUSTOM_EXTENSION:
                case DEVELOPMENT_BECOME_ANY_ACCOUNT:
                case HTTP:
                case LDAP_BIND:
                case OAUTH:
                case OPENID:
                case OPENID_SSO:
                default:
                    String msg = "user \"%s\" not found";
                    logger.atSevere().withCause(e).log(msg, token);
                    throw new CmdLineException(owner, localizable(msg), token);
            }
        }
    } catch (StorageException e) {
        CmdLineException newException = new CmdLineException(owner, localizable("database is down"));
        newException.initCause(e);
        throw newException;
    } catch (IOException e) {
        throw new CmdLineException(owner, "Failed to load account", e);
    } catch (ConfigInvalidException e) {
        throw new CmdLineException(owner, "Invalid account config", e);
    }
    setter.addValue(accountId);
    return 1;
}
Also used : Account(com.google.gerrit.entities.Account) UnprocessableEntityException(com.google.gerrit.extensions.restapi.UnprocessableEntityException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) IOException(java.io.IOException) StorageException(com.google.gerrit.exceptions.StorageException) CmdLineException(org.kohsuke.args4j.CmdLineException)

Aggregations

ConfigInvalidException (org.eclipse.jgit.errors.ConfigInvalidException)158 IOException (java.io.IOException)95 Inject (com.google.inject.Inject)38 Repository (org.eclipse.jgit.lib.Repository)37 Provider (com.google.inject.Provider)34 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)31 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)30 ArrayList (java.util.ArrayList)30 Account (com.google.gerrit.entities.Account)27 List (java.util.List)26 Set (java.util.Set)26 ObjectId (org.eclipse.jgit.lib.ObjectId)26 AuthException (com.google.gerrit.extensions.restapi.AuthException)25 Config (org.eclipse.jgit.lib.Config)24 Singleton (com.google.inject.Singleton)23 OrmException (com.google.gwtorm.server.OrmException)22 AccountGroup (com.google.gerrit.entities.AccountGroup)21 RevWalk (org.eclipse.jgit.revwalk.RevWalk)21 StorageException (com.google.gerrit.exceptions.StorageException)20 BadRequestException (com.google.gerrit.extensions.restapi.BadRequestException)20