Search in sources :

Example 1 with AuthType

use of com.google.gerrit.extensions.client.AuthType in project gerrit by GerritCodeReview.

the class JettyServer method listen.

private Connector[] listen(Server server, Config cfg) {
    // OpenID and certain web-based single-sign-on products can cause
    // some very long headers, especially in the Referer header. We
    // need to use a larger default header size to ensure we have
    // the space required.
    // 
    final int requestHeaderSize = cfg.getInt("httpd", "requestheadersize", 16386);
    final URI[] listenUrls = listenURLs(cfg);
    final boolean reuseAddress = cfg.getBoolean("httpd", "reuseaddress", true);
    final int acceptors = cfg.getInt("httpd", "acceptorThreads", 2);
    final AuthType authType = cfg.getEnum("auth", null, "type", AuthType.OPENID);
    reverseProxy = isReverseProxied(listenUrls);
    final Connector[] connectors = new Connector[listenUrls.length];
    for (int idx = 0; idx < listenUrls.length; idx++) {
        final URI u = listenUrls[idx];
        final int defaultPort;
        final ServerConnector c;
        HttpConfiguration config = defaultConfig(requestHeaderSize);
        if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType) && !"https".equals(u.getScheme())) {
            throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' " + " not supported in httpd.listenurl '" + u + "' when auth.type = '" + AuthType.CLIENT_SSL_CERT_LDAP.name() + "'; only 'https' is supported");
        }
        if ("http".equals(u.getScheme())) {
            defaultPort = 80;
            c = newServerConnector(server, acceptors, config);
        } else if ("https".equals(u.getScheme())) {
            SslContextFactory.Server ssl = new SslContextFactory.Server();
            final Path keystore = getFile(cfg, "sslkeystore", "etc/keystore");
            String password = cfg.getString("httpd", null, "sslkeypassword");
            if (password == null) {
                password = "gerrit";
            }
            ssl.setKeyStorePath(keystore.toAbsolutePath().toString());
            ssl.setTrustStorePath(keystore.toAbsolutePath().toString());
            ssl.setKeyStorePassword(password);
            ssl.setTrustStorePassword(password);
            if (AuthType.CLIENT_SSL_CERT_LDAP.equals(authType)) {
                ssl.setNeedClientAuth(true);
                Path crl = getFile(cfg, "sslCrl", "etc/crl.pem");
                if (Files.exists(crl)) {
                    ssl.setCrlPath(crl.toAbsolutePath().toString());
                    ssl.setValidatePeerCerts(true);
                }
            }
            defaultPort = 443;
            config.addCustomizer(new SecureRequestCustomizer());
            c = new ServerConnector(server, null, null, null, 0, acceptors, new SslConnectionFactory(ssl, "http/1.1"), new HttpConnectionFactory(config));
        } else if ("proxy-http".equals(u.getScheme())) {
            defaultPort = 8080;
            config.addCustomizer(new ForwardedRequestCustomizer());
            c = newServerConnector(server, acceptors, config);
        } else if ("proxy-https".equals(u.getScheme())) {
            defaultPort = 8080;
            config.addCustomizer(new ForwardedRequestCustomizer());
            config.addCustomizer((connector, channelConfig, request) -> {
                request.setScheme(HttpScheme.HTTPS.asString());
                request.setSecure(true);
            });
            c = newServerConnector(server, acceptors, config);
        } else {
            throw new IllegalArgumentException("Protocol '" + u.getScheme() + "' " + " not supported in httpd.listenurl '" + u + "';" + " only 'http', 'https', 'proxy-http, 'proxy-https'" + " are supported");
        }
        try {
            if (u.getHost() == null && (// 
            u.getAuthority().equals("*") || u.getAuthority().startsWith("*:"))) {
                // Bind to all local addresses. Port wasn't parsed right by URI
                // due to the illegal host of "*" so replace with a legal name
                // and parse the URI.
                // 
                final URI r = new URI(u.toString().replace('*', 'A')).parseServerAuthority();
                c.setHost(null);
                c.setPort(0 < r.getPort() ? r.getPort() : defaultPort);
            } else {
                final URI r = u.parseServerAuthority();
                c.setHost(r.getHost());
                c.setPort(0 <= r.getPort() ? r.getPort() : defaultPort);
            }
        } catch (URISyntaxException e) {
            throw new IllegalArgumentException("Invalid httpd.listenurl " + u, e);
        }
        c.setInheritChannel(cfg.getBoolean("httpd", "inheritChannel", false));
        c.setReuseAddress(reuseAddress);
        c.setIdleTimeout(cfg.getTimeUnit("httpd", null, "idleTimeout", 30000L, MILLISECONDS));
        connectors[idx] = c;
    }
    return connectors;
}
Also used : Path(java.nio.file.Path) ServletContextHandler(org.eclipse.jetty.servlet.ServletContextHandler) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) LifecycleListener(com.google.gerrit.extensions.events.LifecycleListener) ContextHandlerCollection(org.eclipse.jetty.server.handler.ContextHandlerCollection) Inject(com.google.inject.Inject) URISyntaxException(java.net.URISyntaxException) DefaultServlet(org.eclipse.jetty.servlet.DefaultServlet) MBeanContainer(org.eclipse.jetty.jmx.MBeanContainer) Config(org.eclipse.jgit.lib.Config) FilterHolder(org.eclipse.jetty.servlet.FilterHolder) QueuedThreadPool(org.eclipse.jetty.util.thread.QueuedThreadPool) Map(java.util.Map) StatisticsHandler(org.eclipse.jetty.server.handler.StatisticsHandler) Filter(javax.servlet.Filter) URI(java.net.URI) GuiceServletContextListener(com.google.inject.servlet.GuiceServletContextListener) Path(java.nio.file.Path) Server(org.eclipse.jetty.server.Server) BlockingArrayQueue(org.eclipse.jetty.util.BlockingArrayQueue) EnumSet(java.util.EnumSet) GerritServerConfig(com.google.gerrit.server.config.GerritServerConfig) HttpSessionListener(javax.servlet.http.HttpSessionListener) ServletHolder(org.eclipse.jetty.servlet.ServletHolder) GuiceFilter(com.google.inject.servlet.GuiceFilter) Set(java.util.Set) MILLISECONDS(java.util.concurrent.TimeUnit.MILLISECONDS) List(java.util.List) Singleton(com.google.inject.Singleton) AuthType(com.google.gerrit.extensions.client.AuthType) Handler(org.eclipse.jetty.server.Handler) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) ThreadSettingsConfig(com.google.gerrit.server.config.ThreadSettingsConfig) HttpScheme(org.eclipse.jetty.http.HttpScheme) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) HashMap(java.util.HashMap) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) ConnectionStatistics(org.eclipse.jetty.io.ConnectionStatistics) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Strings(com.google.common.base.Strings) HttpLogFactory(com.google.gerrit.pgm.http.jetty.HttpLog.HttpLogFactory) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) HttpSessionEvent(javax.servlet.http.HttpSessionEvent) ManagementFactory(java.lang.management.ManagementFactory) Files(java.nio.file.Files) ContextHandler(org.eclipse.jetty.server.handler.ContextHandler) SessionHandler(org.eclipse.jetty.server.session.SessionHandler) Injector(com.google.inject.Injector) TimeUnit(java.util.concurrent.TimeUnit) AtomicLong(java.util.concurrent.atomic.AtomicLong) RequestLogHandler(org.eclipse.jetty.server.handler.RequestLogHandler) ServerConnector(org.eclipse.jetty.server.ServerConnector) Log(org.eclipse.jetty.util.log.Log) SitePaths(com.google.gerrit.server.config.SitePaths) DispatcherType(javax.servlet.DispatcherType) VisibleForTesting(com.google.common.annotations.VisibleForTesting) Connector(org.eclipse.jetty.server.Connector) SECONDS(java.util.concurrent.TimeUnit.SECONDS) ServerConnector(org.eclipse.jetty.server.ServerConnector) Connector(org.eclipse.jetty.server.Connector) SecureRequestCustomizer(org.eclipse.jetty.server.SecureRequestCustomizer) Server(org.eclipse.jetty.server.Server) HttpConnectionFactory(org.eclipse.jetty.server.HttpConnectionFactory) HttpConfiguration(org.eclipse.jetty.server.HttpConfiguration) URISyntaxException(java.net.URISyntaxException) SslConnectionFactory(org.eclipse.jetty.server.SslConnectionFactory) URI(java.net.URI) ForwardedRequestCustomizer(org.eclipse.jetty.server.ForwardedRequestCustomizer) ServerConnector(org.eclipse.jetty.server.ServerConnector) SslContextFactory(org.eclipse.jetty.util.ssl.SslContextFactory) AuthType(com.google.gerrit.extensions.client.AuthType)

Example 2 with AuthType

use of com.google.gerrit.extensions.client.AuthType in project gerrit by GerritCodeReview.

the class DeleteEmail method apply.

public Response<?> apply(IdentifiedUser user, String email) throws ResourceNotFoundException, ResourceConflictException, MethodNotAllowedException, IOException, ConfigInvalidException {
    Account.Id accountId = user.getAccountId();
    if (realm.accountBelongsToRealm(externalIds.byAccount(accountId)) && !realm.allowsEdit(AccountFieldName.REGISTER_NEW_EMAIL)) {
        throw new MethodNotAllowedException("realm does not allow deleting emails");
    }
    Set<ExternalId> extIds = externalIds.byAccount(accountId).stream().filter(e -> email.equals(e.email())).collect(toSet());
    if (extIds.isEmpty()) {
        throw new ResourceNotFoundException(email);
    }
    if (realm.accountBelongsToRealm(extIds)) {
        String errorMsg = String.format("Cannot remove e-mail '%s' which is directly associated with %s authentication", email, authType);
        throw new ResourceConflictException(errorMsg);
    }
    try {
        accountManager.unlink(user.getAccountId(), extIds.stream().map(ExternalId::key).collect(toSet()));
    } catch (AccountException e) {
        throw new ResourceConflictException(e.getMessage());
    }
    return Response.none();
}
Also used : ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException) AuthType(com.google.gerrit.extensions.client.AuthType) PermissionBackendException(com.google.gerrit.server.permissions.PermissionBackendException) ConfigInvalidException(org.eclipse.jgit.errors.ConfigInvalidException) Inject(com.google.inject.Inject) Input(com.google.gerrit.extensions.common.Input) Response(com.google.gerrit.extensions.restapi.Response) PermissionBackend(com.google.gerrit.server.permissions.PermissionBackend) RestModifyView(com.google.gerrit.extensions.restapi.RestModifyView) AuthException(com.google.gerrit.extensions.restapi.AuthException) Collectors.toSet(java.util.stream.Collectors.toSet) GlobalPermission(com.google.gerrit.server.permissions.GlobalPermission) CurrentUser(com.google.gerrit.server.CurrentUser) AccountResource(com.google.gerrit.server.account.AccountResource) Account(com.google.gerrit.entities.Account) Set(java.util.Set) AccountFieldName(com.google.gerrit.extensions.client.AccountFieldName) IOException(java.io.IOException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalIds(com.google.gerrit.server.account.externalids.ExternalIds) Provider(com.google.inject.Provider) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) IdentifiedUser(com.google.gerrit.server.IdentifiedUser) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) AuthConfig(com.google.gerrit.server.config.AuthConfig) Realm(com.google.gerrit.server.account.Realm) AccountManager(com.google.gerrit.server.account.AccountManager) Singleton(com.google.inject.Singleton) Account(com.google.gerrit.entities.Account) ResourceConflictException(com.google.gerrit.extensions.restapi.ResourceConflictException) MethodNotAllowedException(com.google.gerrit.extensions.restapi.MethodNotAllowedException) AccountException(com.google.gerrit.server.account.AccountException) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ResourceNotFoundException(com.google.gerrit.extensions.restapi.ResourceNotFoundException)

Example 3 with AuthType

use of com.google.gerrit.extensions.client.AuthType in project gerrit by GerritCodeReview.

the class InitAdminUser method postRun.

@Override
public void postRun() throws Exception {
    if (!accounts.hasAnyAccount()) {
        welcome();
    }
    AuthType authType = flags.cfg.getEnum(AuthType.values(), "auth", null, "type", null);
    if (authType != AuthType.DEVELOPMENT_BECOME_ANY_ACCOUNT) {
        return;
    }
    if (!accounts.hasAnyAccount()) {
        ui.header("Gerrit Administrator");
        if (ui.yesno(true, "Create administrator user")) {
            Account.Id id = Account.id(sequencesOnInit.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(externalIdFactory.createUsername(username, id, httpPassword));
            if (email != null) {
                extIds.add(externalIdFactory.createEmail(id, email));
            }
            externalIds.insert("Add external IDs for initial admin user", extIds);
            Account persistedAccount = accounts.insert(Account.builder(id, TimeUtil.now()).setFullName(name).setPreferredEmail(email));
            // Only two groups should exist at this point in time and hence iterating over all of them
            // is cheap.
            Optional<GroupReference> adminGroupReference = groupsOnInit.getAllGroupReferences().filter(group -> group.getName().equals("Administrators")).findAny();
            if (!adminGroupReference.isPresent()) {
                throw new NoSuchGroupException("Administrators");
            }
            GroupReference adminGroup = adminGroupReference.get();
            groupsOnInit.addGroupMember(adminGroup.getUUID(), persistedAccount);
            if (sshKey != null) {
                VersionedAuthorizedKeysOnInit authorizedKeys = authorizedKeysFactory.create(id).load();
                authorizedKeys.addKey(sshKey.sshPublicKey());
                authorizedKeys.save("Add SSH key for initial admin user\n");
            }
            AccountState as = AccountState.forAccount(persistedAccount, extIds);
            for (AccountIndex accountIndex : accountIndexCollection.getWriteIndexes()) {
                accountIndex.replace(as);
            }
            InternalGroup adminInternalGroup = groupsOnInit.getExistingGroup(adminGroup);
            for (GroupIndex groupIndex : groupIndexCollection.getWriteIndexes()) {
                groupIndex.replace(adminInternalGroup);
            }
        }
    }
}
Also used : InternalGroup(com.google.gerrit.entities.InternalGroup) AuthType(com.google.gerrit.extensions.client.AuthType) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) Inject(com.google.inject.Inject) GroupIndexCollection(com.google.gerrit.server.index.group.GroupIndexCollection) InitStep(com.google.gerrit.pgm.init.api.InitStep) EmailValidator(org.apache.commons.validator.routines.EmailValidator) ArrayList(java.util.ArrayList) Strings(com.google.common.base.Strings) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) ExternalIdFactory(com.google.gerrit.server.account.externalids.ExternalIdFactory) ConsoleUI(com.google.gerrit.pgm.init.api.ConsoleUI) Path(java.nio.file.Path) Files(java.nio.file.Files) UTF_8(java.nio.charset.StandardCharsets.UTF_8) Account(com.google.gerrit.entities.Account) AccountIndexCollection(com.google.gerrit.server.index.account.AccountIndexCollection) IOException(java.io.IOException) GroupReference(com.google.gerrit.entities.GroupReference) List(java.util.List) AccountSshKey(com.google.gerrit.server.account.AccountSshKey) Paths(java.nio.file.Paths) Optional(java.util.Optional) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) GroupIndex(com.google.gerrit.server.index.group.GroupIndex) TimeUtil(com.google.gerrit.server.util.time.TimeUtil) AccountState(com.google.gerrit.server.account.AccountState) SequencesOnInit(com.google.gerrit.pgm.init.api.SequencesOnInit) InitFlags(com.google.gerrit.pgm.init.api.InitFlags) Account(com.google.gerrit.entities.Account) AccountIndex(com.google.gerrit.server.index.account.AccountIndex) AccountSshKey(com.google.gerrit.server.account.AccountSshKey) ExternalId(com.google.gerrit.server.account.externalids.ExternalId) ArrayList(java.util.ArrayList) AccountState(com.google.gerrit.server.account.AccountState) NoSuchGroupException(com.google.gerrit.exceptions.NoSuchGroupException) InternalGroup(com.google.gerrit.entities.InternalGroup) GroupIndex(com.google.gerrit.server.index.group.GroupIndex) AuthType(com.google.gerrit.extensions.client.AuthType) GroupReference(com.google.gerrit.entities.GroupReference)

Aggregations

AuthType (com.google.gerrit.extensions.client.AuthType)3 Inject (com.google.inject.Inject)3 Strings (com.google.common.base.Strings)2 Account (com.google.gerrit.entities.Account)2 ExternalId (com.google.gerrit.server.account.externalids.ExternalId)2 Singleton (com.google.inject.Singleton)2 IOException (java.io.IOException)2 Set (java.util.Set)2 VisibleForTesting (com.google.common.annotations.VisibleForTesting)1 GroupReference (com.google.gerrit.entities.GroupReference)1 InternalGroup (com.google.gerrit.entities.InternalGroup)1 NoSuchGroupException (com.google.gerrit.exceptions.NoSuchGroupException)1 AccountFieldName (com.google.gerrit.extensions.client.AccountFieldName)1 Input (com.google.gerrit.extensions.common.Input)1 LifecycleListener (com.google.gerrit.extensions.events.LifecycleListener)1 AuthException (com.google.gerrit.extensions.restapi.AuthException)1 MethodNotAllowedException (com.google.gerrit.extensions.restapi.MethodNotAllowedException)1 ResourceConflictException (com.google.gerrit.extensions.restapi.ResourceConflictException)1 ResourceNotFoundException (com.google.gerrit.extensions.restapi.ResourceNotFoundException)1 Response (com.google.gerrit.extensions.restapi.Response)1