Java Code Examples for org.apache.pulsar.broker.ServiceConfiguration#setTlsKeyFilePath()

The following examples show how to use org.apache.pulsar.broker.ServiceConfiguration#setTlsKeyFilePath() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: BrokerAdminClientTlsAuthTest.java    From pulsar with Apache License 2.0 6 votes vote down vote up
private void buildConf(ServiceConfiguration conf) {
    conf.setLoadBalancerEnabled(true);
    conf.setTlsCertificateFilePath(getTLSFile("broker.cert"));
    conf.setTlsKeyFilePath(getTLSFile("broker.key-pk8"));
    conf.setTlsTrustCertsFilePath(getTLSFile("ca.cert"));
    conf.setAuthenticationEnabled(true);
    conf.setSuperUserRoles(ImmutableSet.of("superproxy", "broker.pulsar.apache.org"));
    conf.setAuthenticationProviders(
            ImmutableSet.of("org.apache.pulsar.broker.authentication.AuthenticationProviderTls"));
    conf.setAuthorizationEnabled(true);
    conf.setBrokerClientTlsEnabled(true);
    String str = String.format("tlsCertFile:%s,tlsKeyFile:%s", getTLSFile("broker.cert"), getTLSFile("broker.key-pk8"));
    conf.setBrokerClientAuthenticationParameters(str);
    conf.setBrokerClientAuthenticationPlugin("org.apache.pulsar.client.impl.auth.AuthenticationTls");
    conf.setBrokerClientTrustCertsFilePath(getTLSFile("ca.cert"));
    conf.setTlsAllowInsecureConnection(true);
}
 
Example 2
Source File: BrokerServiceLookupTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
/**
 * 1. Start broker1 and broker2 with tls enable 2. Hit HTTPS lookup url at broker2 which redirects to HTTPS broker1
 *
 * @throws Exception
 */
@Test
public void testWebserviceServiceTls() throws Exception {
    log.info("-- Starting {} test --", methodName);
    final String TLS_SERVER_CERT_FILE_PATH = "./src/test/resources/certificate/server.crt";
    final String TLS_SERVER_KEY_FILE_PATH = "./src/test/resources/certificate/server.key";
    final String TLS_CLIENT_CERT_FILE_PATH = "./src/test/resources/certificate/client.crt";
    final String TLS_CLIENT_KEY_FILE_PATH = "./src/test/resources/certificate/client.key";

    /**** start broker-2 ****/
    ServiceConfiguration conf2 = new ServiceConfiguration();
    conf2.setAdvertisedAddress("localhost");
    conf2.setBrokerServicePort(Optional.of(0));
    conf2.setBrokerServicePortTls(Optional.of(0));
    conf2.setWebServicePort(Optional.of(0));
    conf2.setWebServicePortTls(Optional.of(0));
    conf2.setAdvertisedAddress("localhost");
    conf2.setTlsAllowInsecureConnection(true);
    conf2.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
    conf2.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
    conf2.setClusterName(conf.getClusterName());
    conf2.setZookeeperServers("localhost:2181");

    @Cleanup
    PulsarService pulsar2 = startBroker(conf2);

    // restart broker1 with tls enabled
    conf.setBrokerServicePortTls(Optional.of(0));
    conf.setWebServicePortTls(Optional.of(0));
    conf.setTlsAllowInsecureConnection(true);
    conf.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
    conf.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
    stopBroker();
    startBroker();
    pulsar.getLoadManager().get().writeLoadReportOnZookeeper();
    pulsar2.getLoadManager().get().writeLoadReportOnZookeeper();

    LoadManager loadManager1 = spy(pulsar.getLoadManager().get());
    LoadManager loadManager2 = spy(pulsar2.getLoadManager().get());
    Field loadManagerField = NamespaceService.class.getDeclaredField("loadManager");
    loadManagerField.setAccessible(true);

    // mock: redirect request to leader [2]
    doReturn(true).when(loadManager2).isCentralized();
    loadManagerField.set(pulsar2.getNamespaceService(), new AtomicReference<>(loadManager2));
    loadManagerField.set(pulsar.getNamespaceService(), new AtomicReference<>(loadManager1));

    // mock: return Broker2 as a Least-loaded broker when leader receives
    // request [3]
    doReturn(true).when(loadManager1).isCentralized();
    doReturn(true).when(loadManager2).isCentralized();
    SimpleResourceUnit resourceUnit = new SimpleResourceUnit(pulsar.getWebServiceAddress(), null);
    doReturn(Optional.of(resourceUnit)).when(loadManager2).getLeastLoaded(any(ServiceUnitId.class));
    doReturn(Optional.of(resourceUnit)).when(loadManager1).getLeastLoaded(any(ServiceUnitId.class));


    /**** started broker-2 ****/

    URI brokerServiceUrl = new URI("pulsar://localhost:" + conf2.getBrokerServicePort().get());
    @Cleanup
    PulsarClient pulsarClient2 = PulsarClient.builder().serviceUrl(brokerServiceUrl.toString()).build();

    final String lookupResourceUrl = "/lookup/v2/topic/persistent/my-property/my-ns/my-topic1";

    // set client cert_key file
    KeyManager[] keyManagers = null;
    Certificate[] tlsCert = SecurityUtility.loadCertificatesFromPemFile(TLS_CLIENT_CERT_FILE_PATH);
    PrivateKey tlsKey = SecurityUtility.loadPrivateKeyFromPemFile(TLS_CLIENT_KEY_FILE_PATH);
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(null, null);
    ks.setKeyEntry("private", tlsKey, "".toCharArray(), tlsCert);
    KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
    kmf.init(ks, "".toCharArray());
    keyManagers = kmf.getKeyManagers();
    TrustManager[] trustManagers = InsecureTrustManagerFactory.INSTANCE.getTrustManagers();
    SSLContext sslCtx = SSLContext.getInstance("TLS");
    sslCtx.init(keyManagers, trustManagers, new SecureRandom());
    HttpsURLConnection.setDefaultSSLSocketFactory(sslCtx.getSocketFactory());

    // hit broker2 url
    URLConnection con = new URL(pulsar2.getWebServiceAddressTls() + lookupResourceUrl).openConnection();
    log.info("orignal url: {}", con.getURL());
    con.connect();
    log.info("connected url: {} ", con.getURL());
    // assert connect-url: broker2-https
    assertEquals(new Integer(con.getURL().getPort()), conf2.getWebServicePortTls().get());
    InputStream is = con.getInputStream();
    // assert redirect-url: broker1-https only
    log.info("redirected url: {}", con.getURL());
    assertEquals(new Integer(con.getURL().getPort()), conf.getWebServicePortTls().get());
    is.close();

    loadManager1 = null;
    loadManager2 = null;
}
 
Example 3
Source File: WebServiceTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
private void setupEnv(boolean enableFilter, String minApiVersion, boolean allowUnversionedClients,
        boolean enableTls, boolean enableAuth, boolean allowInsecure) throws Exception {
    Set<String> providers = new HashSet<>();
    providers.add("org.apache.pulsar.broker.authentication.AuthenticationProviderTls");

    Set<String> roles = new HashSet<>();
    roles.add("client");

    ServiceConfiguration config = new ServiceConfiguration();
    config.setAdvertisedAddress("localhost");
    config.setBrokerServicePort(Optional.of(0));
    config.setWebServicePort(Optional.of(0));
    if (enableTls) {
        config.setWebServicePortTls(Optional.of(0));
    }
    config.setClientLibraryVersionCheckEnabled(enableFilter);
    config.setAuthenticationEnabled(enableAuth);
    config.setAuthenticationProviders(providers);
    config.setAuthorizationEnabled(false);
    config.setSuperUserRoles(roles);
    config.setTlsCertificateFilePath(TLS_SERVER_CERT_FILE_PATH);
    config.setTlsKeyFilePath(TLS_SERVER_KEY_FILE_PATH);
    config.setTlsAllowInsecureConnection(allowInsecure);
    config.setTlsTrustCertsFilePath(allowInsecure ? "" : TLS_CLIENT_CERT_FILE_PATH);
    config.setClusterName("local");
    config.setAdvertisedAddress("localhost"); // TLS certificate expects localhost
    config.setZookeeperServers("localhost:2181");
    config.setHttpMaxRequestSize(10 * 1024);
    pulsar = spy(new PulsarService(config));
    doReturn(zkFactory).when(pulsar).getZooKeeperClientFactory();
    doReturn(new MockedBookKeeperClientFactory()).when(pulsar).newBookKeeperClientFactory();
    pulsar.start();

    try {
        pulsar.getZkClient().delete("/minApiVersion", -1);
    } catch (Exception ex) {
    }
    pulsar.getZkClient().create("/minApiVersion", minApiVersion.getBytes(), null, CreateMode.PERSISTENT);

    String BROKER_URL_BASE = "http://localhost:" + pulsar.getListenPortHTTP().get();
    String BROKER_URL_BASE_TLS = "https://localhost:" + pulsar.getListenPortHTTPS().orElse(-1);
    String serviceUrl = BROKER_URL_BASE;

    PulsarAdminBuilder adminBuilder = PulsarAdmin.builder();
    if (enableTls && enableAuth) {
        serviceUrl = BROKER_URL_BASE_TLS;

        Map<String, String> authParams = new HashMap<>();
        authParams.put("tlsCertFile", TLS_CLIENT_CERT_FILE_PATH);
        authParams.put("tlsKeyFile", TLS_CLIENT_KEY_FILE_PATH);

        adminBuilder.authentication(AuthenticationTls.class.getName(), authParams).allowTlsInsecureConnection(true);
    }

    BROKER_LOOKUP_URL = BROKER_URL_BASE
            + "/lookup/v2/destination/persistent/my-property/local/my-namespace/my-topic";
    BROKER_LOOKUP_URL_TLS = BROKER_URL_BASE_TLS
            + "/lookup/v2/destination/persistent/my-property/local/my-namespace/my-topic";

    PulsarAdmin pulsarAdmin = adminBuilder.serviceHttpUrl(serviceUrl).build();

    try {
        pulsarAdmin.clusters().createCluster(config.getClusterName(),
                new ClusterData(pulsar.getSafeWebServiceAddress()));
    } catch (ConflictException ce) {
        // This is OK.
    } finally {
        pulsarAdmin.close();
    }
}