Search in sources :

Example 6 with AccountSshKey

use of com.google.gerrit.reviewdb.client.AccountSshKey in project gerrit by GerritCodeReview.

the class Schema_124 method fixInvalidSequenceNumbers.

private Collection<AccountSshKey> fixInvalidSequenceNumbers(Collection<AccountSshKey> keys) {
    Ordering<AccountSshKey> o = Ordering.from(comparing(k -> k.getKey().get()));
    List<AccountSshKey> fixedKeys = new ArrayList<>(keys);
    AccountSshKey minKey = o.min(keys);
    while (minKey.getKey().get() <= 0) {
        AccountSshKey fixedKey = new AccountSshKey(new AccountSshKey.Id(minKey.getKey().getParentKey(), Math.max(o.max(keys).getKey().get() + 1, 1)), minKey.getSshPublicKey());
        Collections.replaceAll(fixedKeys, minKey, fixedKey);
        minKey = o.min(fixedKeys);
    }
    return fixedKeys;
}
Also used : VersionedAuthorizedKeys(com.google.gerrit.server.account.VersionedAuthorizedKeys) SimpleSshKeyCreator(com.google.gerrit.server.account.VersionedAuthorizedKeys.SimpleSshKeyCreator) AllUsersName(com.google.gerrit.server.config.AllUsersName) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb) OrmException(com.google.gwtorm.server.OrmException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) ListMultimap(com.google.common.collect.ListMultimap) MultimapBuilder(com.google.common.collect.MultimapBuilder) JdbcSchema(com.google.gwtorm.jdbc.JdbcSchema) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate) Inject(com.google.inject.Inject) ArrayList(java.util.ArrayList) RevWalk(org.eclipse.jgit.revwalk.RevWalk) Strings(com.google.common.base.Strings) SQLException(java.sql.SQLException) Account(com.google.gerrit.reviewdb.client.Account) ResultSet(java.sql.ResultSet) Map(java.util.Map) Comparator.comparing(java.util.Comparator.comparing) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) Collection(java.util.Collection) IOException(java.io.IOException) NullProgressMonitor(org.eclipse.jgit.lib.NullProgressMonitor) PersonIdent(org.eclipse.jgit.lib.PersonIdent) Provider(com.google.inject.Provider) List(java.util.List) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) Ordering(com.google.common.collect.Ordering) GitRepositoryManager(com.google.gerrit.server.git.GitRepositoryManager) Statement(java.sql.Statement) Collections(java.util.Collections) GerritPersonIdent(com.google.gerrit.server.GerritPersonIdent) GitReferenceUpdated(com.google.gerrit.server.extensions.events.GitReferenceUpdated) Repository(org.eclipse.jgit.lib.Repository) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) ArrayList(java.util.ArrayList)

Example 7 with AccountSshKey

use of com.google.gerrit.reviewdb.client.AccountSshKey in project gerrit by GerritCodeReview.

the class Schema_124 method migrateData.

@Override
protected void migrateData(ReviewDb db, UpdateUI ui) throws OrmException, SQLException {
    ListMultimap<Account.Id, AccountSshKey> imports = MultimapBuilder.hashKeys().arrayListValues().build();
    try (Statement stmt = ((JdbcSchema) db).getConnection().createStatement();
        ResultSet rs = stmt.executeQuery("SELECT " + "account_id, " + "seq, " + "ssh_public_key, " + "valid " + "FROM account_ssh_keys")) {
        while (rs.next()) {
            Account.Id accountId = new Account.Id(rs.getInt(1));
            int seq = rs.getInt(2);
            String sshPublicKey = rs.getString(3);
            AccountSshKey key = new AccountSshKey(new AccountSshKey.Id(accountId, seq), sshPublicKey);
            boolean valid = toBoolean(rs.getString(4));
            if (!valid) {
                key.setInvalid();
            }
            imports.put(accountId, key);
        }
    }
    if (imports.isEmpty()) {
        return;
    }
    try (Repository git = repoManager.openRepository(allUsersName);
        RevWalk rw = new RevWalk(git)) {
        BatchRefUpdate bru = git.getRefDatabase().newBatchUpdate();
        for (Map.Entry<Account.Id, Collection<AccountSshKey>> e : imports.asMap().entrySet()) {
            try (MetaDataUpdate md = new MetaDataUpdate(GitReferenceUpdated.DISABLED, allUsersName, git, bru)) {
                md.getCommitBuilder().setAuthor(serverUser);
                md.getCommitBuilder().setCommitter(serverUser);
                VersionedAuthorizedKeys authorizedKeys = new VersionedAuthorizedKeys(new SimpleSshKeyCreator(), e.getKey());
                authorizedKeys.load(md);
                authorizedKeys.setKeys(fixInvalidSequenceNumbers(e.getValue()));
                authorizedKeys.commit(md);
            }
        }
        bru.execute(rw, NullProgressMonitor.INSTANCE);
    } catch (ConfigInvalidException | IOException ex) {
        throw new OrmException(ex);
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) Statement(java.sql.Statement) IOException(java.io.IOException) RevWalk(org.eclipse.jgit.revwalk.RevWalk) SimpleSshKeyCreator(com.google.gerrit.server.account.VersionedAuthorizedKeys.SimpleSshKeyCreator) Repository(org.eclipse.jgit.lib.Repository) OrmException(com.google.gwtorm.server.OrmException) ResultSet(java.sql.ResultSet) Collection(java.util.Collection) VersionedAuthorizedKeys(com.google.gerrit.server.account.VersionedAuthorizedKeys) Map(java.util.Map) BatchRefUpdate(org.eclipse.jgit.lib.BatchRefUpdate) MetaDataUpdate(com.google.gerrit.server.git.MetaDataUpdate)

Example 8 with AccountSshKey

use of com.google.gerrit.reviewdb.client.AccountSshKey in project gerrit by GerritCodeReview.

the class VersionedAuthorizedKeys method markKeyInvalid.

/**
   * Marks the SSH key with the given sequence number as invalid.
   *
   * @param seq the sequence number
   * @return <code>true</code> if a key with this sequence number was found and marked as invalid,
   *     <code>false</code> if no key with the given sequence number exists or if the key was
   *     already marked as invalid
   */
private boolean markKeyInvalid(int seq) {
    checkLoaded();
    AccountSshKey key = getKey(seq);
    if (key != null && key.isValid()) {
        key.setInvalid();
        return true;
    }
    return false;
}
Also used : AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey)

Example 9 with AccountSshKey

use of com.google.gerrit.reviewdb.client.AccountSshKey in project gerrit by GerritCodeReview.

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    try (ReviewDb db = dbFactory.open()) {
        if (db.accounts().anyAccounts().toList().isEmpty()) {
            ui.header("Gerrit Administrator");
            if (ui.yesno(true, "Create administrator user")) {
                Account.Id id = new Account.Id(db.nextAccountId());
                String username = ui.readString("admin", "username");
                String name = ui.readString("Administrator", "name");
                String httpPassword = ui.readString("secret", "HTTP password");
                AccountSshKey sshKey = readSshKey(id);
                String email = readEmail(sshKey);
                List<ExternalId> extIds = new ArrayList<>(2);
                extIds.add(ExternalId.createUsername(username, id, httpPassword));
                if (email != null) {
                    extIds.add(ExternalId.createEmail(id, email));
                }
                externalIds.insert("Add external IDs for initial admin user", extIds);
                Account a = new Account(id, TimeUtil.nowTs());
                a.setFullName(name);
                a.setPreferredEmail(email);
                accounts.insert(db, a);
                AccountGroupName adminGroupName = db.accountGroupNames().get(new AccountGroup.NameKey("Administrators"));
                AccountGroupMember m = new AccountGroupMember(new AccountGroupMember.Key(id, adminGroupName.getId()));
                db.accountGroupMembers().insert(Collections.singleton(m));
                if (sshKey != null) {
                    VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                    authorizedKeys.addKey(sshKey.getSshPublicKey());
                    authorizedKeys.save("Add SSH key for initial admin user\n");
                }
                AccountGroup adminGroup = db.accountGroups().get(adminGroupName.getId());
                AccountState as = new AccountState(a, Collections.singleton(adminGroup.getGroupUUID()), extIds, new HashMap<>());
                for (AccountIndex accountIndex : indexCollection.getWriteIndexes()) {
                    accountIndex.replace(as);
                }
            }
        }
    }
}
Also used : Account(com.google.gerrit.reviewdb.client.Account) AccountGroupName(com.google.gerrit.reviewdb.client.AccountGroupName) AccountGroupMember(com.google.gerrit.reviewdb.client.AccountGroupMember) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) AccountGroup(com.google.gerrit.reviewdb.client.AccountGroup) AuthType(com.google.gerrit.extensions.client.AuthType) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ReviewDb(com.google.gerrit.reviewdb.server.ReviewDb)

Example 10 with AccountSshKey

use of com.google.gerrit.reviewdb.client.AccountSshKey in project gerrit by GerritCodeReview.

the class AddSshKey method apply.

public Response<SshKeyInfo> apply(IdentifiedUser user, Input input) throws BadRequestException, IOException, ConfigInvalidException {
    if (input == null) {
        input = new Input();
    }
    if (input.raw == null) {
        throw new BadRequestException("SSH public key missing");
    }
    final RawInput rawKey = input.raw;
    String sshPublicKey = new ByteSource() {

        @Override
        public InputStream openStream() throws IOException {
            return rawKey.getInputStream();
        }
    }.asCharSource(UTF_8).read();
    try {
        AccountSshKey sshKey = authorizedKeys.addKey(user.getAccountId(), sshPublicKey);
        try {
            addKeyFactory.create(user, sshKey).send();
        } catch (EmailException e) {
            log.error("Cannot send SSH key added message to " + user.getAccount().getPreferredEmail(), e);
        }
        sshKeyCache.evict(user.getUserName());
        return Response.<SshKeyInfo>created(GetSshKeys.newSshKeyInfo(sshKey));
    } catch (InvalidSshKeyException e) {
        throw new BadRequestException(e.getMessage());
    }
}
Also used : RawInput(com.google.gerrit.extensions.restapi.RawInput) Input(com.google.gerrit.server.account.AddSshKey.Input) InvalidSshKeyException(com.google.gerrit.common.errors.InvalidSshKeyException) SshKeyInfo(com.google.gerrit.extensions.common.SshKeyInfo) AccountSshKey(com.google.gerrit.reviewdb.client.AccountSshKey) RawInput(com.google.gerrit.extensions.restapi.RawInput) EmailException(com.google.gerrit.common.errors.EmailException) BadRequestException(com.google.gerrit.extensions.restapi.BadRequestException) ByteSource(com.google.common.io.ByteSource)

Aggregations

AccountSshKey (com.google.gerrit.reviewdb.client.AccountSshKey)15 Account (com.google.gerrit.reviewdb.client.Account)6 IOException (java.io.IOException)4 ArrayList (java.util.ArrayList)4 InvalidSshKeyException (com.google.gerrit.common.errors.InvalidSshKeyException)3 VersionedAuthorizedKeys (com.google.gerrit.server.account.VersionedAuthorizedKeys)3 MetaDataUpdate (com.google.gerrit.server.git.MetaDataUpdate)3 Collection (java.util.Collection)3 Strings (com.google.common.base.Strings)2 Ordering (com.google.common.collect.Ordering)2 Id (com.google.gerrit.reviewdb.client.AccountSshKey.Id)2 ReviewDb (com.google.gerrit.reviewdb.server.ReviewDb)2 SimpleSshKeyCreator (com.google.gerrit.server.account.VersionedAuthorizedKeys.SimpleSshKeyCreator)2 AllUsersName (com.google.gerrit.server.config.AllUsersName)2 GitRepositoryManager (com.google.gerrit.server.git.GitRepositoryManager)2 OrmException (com.google.gwtorm.server.OrmException)2 Inject (com.google.inject.Inject)2 Provider (com.google.inject.Provider)2 ResultSet (java.sql.ResultSet)2 Statement (java.sql.Statement)2