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

The following examples show how to use org.apache.pulsar.broker.ServiceConfiguration#setAuthorizationEnabled() . 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: MockedPulsarServiceBaseTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
protected PulsarService startBroker(ServiceConfiguration conf) throws Exception {
    PulsarService pulsar = spy(new PulsarService(conf));

    setupBrokerMocks(pulsar);
    boolean isAuthorizationEnabled = conf.isAuthorizationEnabled();
    // enable authorization to initialize authorization service which is used by grant-permission
    conf.setAuthorizationEnabled(true);
    pulsar.start();
    conf.setAuthorizationEnabled(isAuthorizationEnabled);

    return pulsar;
}
 
Example 3
Source File: BkEnsemblesTestBase.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
protected void setup() throws Exception {
    try {
        // start local bookie and zookeeper
        bkEnsemble = new LocalBookkeeperEnsemble(numberOfBookies, 0, () -> 0);
        bkEnsemble.start();

        // start pulsar service
        config = new ServiceConfiguration();
        config.setZookeeperServers("127.0.0.1" + ":" + bkEnsemble.getZookeeperPort());
        config.setAdvertisedAddress("localhost");
        config.setWebServicePort(Optional.of(0));
        config.setClusterName("usc");
        config.setBrokerServicePort(Optional.of(0));
        config.setAuthorizationEnabled(false);
        config.setAuthenticationEnabled(false);
        config.setManagedLedgerMaxEntriesPerLedger(5);
        config.setManagedLedgerMinLedgerRolloverTimeMinutes(0);
        config.setAdvertisedAddress("127.0.0.1");
        config.setAllowAutoTopicCreationType("non-partitioned");

        pulsar = new PulsarService(config);
        pulsar.start();

        admin = PulsarAdmin.builder().serviceHttpUrl(pulsar.getWebServiceAddress()).build();

        admin.clusters().createCluster("usc", new ClusterData(pulsar.getWebServiceAddress()));
        admin.tenants().createTenant("prop",
                new TenantInfo(Sets.newHashSet("appid1"), Sets.newHashSet("usc")));
    } catch (Throwable t) {
        log.error("Error setting up broker test", t);
        Assert.fail("Broker test setup failed");
    }
}
 
Example 4
Source File: MaxMessageSizeTest.java    From pulsar with Apache License 2.0 5 votes vote down vote up
@BeforeMethod
void setup() {
    try {
        bkEnsemble = new LocalBookkeeperEnsemble(3, 0, () -> 0);
        ServerConfiguration conf = new ServerConfiguration();
        conf.setNettyMaxFrameSizeBytes(10 * 1024 * 1024);
        bkEnsemble.startStandalone(conf, false);

        configuration = new ServiceConfiguration();
        configuration.setZookeeperServers("127.0.0.1:" + bkEnsemble.getZookeeperPort());
        configuration.setAdvertisedAddress("localhost");
        configuration.setWebServicePort(Optional.of(0));
        configuration.setClusterName("max_message_test");
        configuration.setBrokerServicePort(Optional.of(0));
        configuration.setAuthorizationEnabled(false);
        configuration.setAuthenticationEnabled(false);
        configuration.setManagedLedgerMaxEntriesPerLedger(5);
        configuration.setManagedLedgerMinLedgerRolloverTimeMinutes(0);
        configuration.setMaxMessageSize(10 * 1024 * 1024);

        pulsar = new PulsarService(configuration);
        pulsar.start();

        String url = "http://127.0.0.1:" + pulsar.getListenPortHTTP().get();
        admin = PulsarAdmin.builder().serviceHttpUrl(url).build();
        admin.clusters().createCluster("max_message_test", new ClusterData(url));
        admin.tenants()
             .createTenant("test", new TenantInfo(Sets.newHashSet("appid1"), Sets.newHashSet("max_message_test")));
        admin.namespaces().createNamespace("test/message", Sets.newHashSet("max_message_test"));
    } catch (Exception e) {
        e.printStackTrace();
    }
}
 
Example 5
Source File: PulsarFunctionsITest.java    From java-specialagent with Apache License 2.0 4 votes vote down vote up
static void start() throws Exception {
  // Start local bookkeeper ensemble
  final LocalBookkeeperEnsemble bkEnsemble = new LocalBookkeeperEnsemble(3, ZOOKEEPER_PORT,TestUtil::nextFreePort);
  bkEnsemble.start();

  final String brokerServiceUrl = "http://127.0.0.1:" + brokerWebServicePort;

  final ServiceConfiguration config = spy(new ServiceConfiguration());
  config.setClusterName(CLUSTER_NAME);
  final Set<String> superUsers = Sets.newHashSet("superUser");
  config.setSuperUserRoles(superUsers);
  config.setWebServicePort(Optional.of(brokerWebServicePort));
  config.setZookeeperServers("127.0.0.1" + ":" + ZOOKEEPER_PORT);
  config.setBrokerServicePort(Optional.of(brokerServicePort));
  config.setLoadManagerClassName(SimpleLoadManagerImpl.class.getName());
  config.setTlsAllowInsecureConnection(true);
  config.setAdvertisedAddress("localhost");

  config.setAuthenticationEnabled(false);
  config.setAuthorizationEnabled(false);

  config.setBrokerClientTlsEnabled(false);
  config.setAllowAutoTopicCreationType("non-partitioned");

  final WorkerService functionsWorkerService = createPulsarFunctionWorker(config);
  final URL urlTls = new URL(brokerServiceUrl);
  final Optional<WorkerService> functionWorkerService = Optional.of(functionsWorkerService);
  try (final PulsarService pulsar = new PulsarService(config, functionWorkerService)) {
    pulsar.start();
    try (final PulsarAdmin admin = PulsarAdmin.builder().serviceHttpUrl(brokerServiceUrl).allowTlsInsecureConnection(true).build()) {
      // update cluster metadata
      final ClusterData clusterData = new ClusterData(urlTls.toString());
      admin.clusters().updateCluster(config.getClusterName(), clusterData);

      final TenantInfo propAdmin = new TenantInfo();
      propAdmin.getAdminRoles().add("superUser");
      propAdmin.setAllowedClusters(Sets.newHashSet(CLUSTER_NAME));
      admin.tenants().updateTenant(tenant, propAdmin);

      final String jarFilePathUrl = Utils.FILE + ":" + ExclamationFunction.class.getProtectionDomain().getCodeSource().getLocation().getPath();

      final ClientBuilder clientBuilder = PulsarClient.builder().serviceUrl(workerConfig.getPulsarServiceUrl());
      try (final PulsarClient pulsarClient = clientBuilder.build()) {
        testE2EPulsarFunction(jarFilePathUrl, admin, pulsarClient);
      }
    }
  }
}
 
Example 6
Source File: WebSocketWebResourceTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
public void setup(Method method) throws Exception {
    MockitoAnnotations.initMocks(this);

    ServiceConfiguration config = new ServiceConfiguration();
    config.setSuperUserRoles(Sets.newHashSet(SUPER_USER));
    if ("testAuthenticationDisabled".equals(method.getName())) {
        config.setAuthenticationEnabled(false);
        config.setAuthorizationEnabled(false);
    } else {
        config.setAuthenticationEnabled(true);
        config.setAuthorizationEnabled(true);
    }

    AuthenticationService authnService = mock(AuthenticationService.class);
    if ("testSuperUserAccess".equals(method.getName())) {
        when(authnService.authenticateHttpRequest(any(HttpServletRequest.class))).thenReturn(SUPER_USER);
    } else if ("testUnauthorizedUserAccess".equals(method.getName())) {
        when(authnService.authenticateHttpRequest(any(HttpServletRequest.class))).thenReturn(UNAUTHORIZED_USER);
    } else if ("testBlankUserAccess".equals(method.getName())) {
        when(authnService.authenticateHttpRequest(any(HttpServletRequest.class))).thenReturn("");
    } else if ("testUnauthenticatedUserAccess".equals(method.getName())) {
        when(authnService.authenticateHttpRequest(any(HttpServletRequest.class)))
                .thenThrow(new AuthenticationException());
    } else {
        when(authnService.authenticateHttpRequest(any(HttpServletRequest.class))).thenReturn(AUTHORIZED_USER);
    }

    AuthorizationService authzService = mock(AuthorizationService.class);
    when(authzService.canLookup(any(TopicName.class), eq(SUPER_USER), any(AuthenticationDataSource.class)))
            .thenReturn(true);
    when(authzService.canLookup(any(TopicName.class), eq(AUTHORIZED_USER), any(AuthenticationDataSource.class)))
            .thenReturn(true);
    when(authzService.canLookup(any(TopicName.class), eq(UNAUTHORIZED_USER), any(AuthenticationDataSource.class)))
            .thenReturn(false);
    when(authzService.canLookup(any(TopicName.class), eq(""), any(AuthenticationDataSource.class)))
            .thenReturn(false);

    WebSocketService socketService = mock(WebSocketService.class);
    when(socketService.getConfig()).thenReturn(config);
    when(socketService.isAuthorizationEnabled()).thenReturn(config.isAuthorizationEnabled());
    when(socketService.getAuthenticationService()).thenReturn(authnService);
    when(socketService.getAuthorizationService()).thenReturn(authzService);

    // Mock WebSocketWebResource
    doReturn(mock(AuthenticationDataHttps.class)).when(webResource).authData();

    // Mock ServletContext
    when(servletContext.getAttribute(anyString())).thenReturn(socketService);

    // Mock UriInfo
    when(uri.getRequestUri()).thenReturn(null);

    topicName = TopicName.get("persistent://tenant/cluster/ns/dest");
}
 
Example 7
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();
    }
}
 
Example 8
Source File: BacklogQuotaManagerTest.java    From pulsar with Apache License 2.0 4 votes vote down vote up
@BeforeMethod
void setup() throws Exception {
    try {
        // start local bookie and zookeeper
        bkEnsemble = new LocalBookkeeperEnsemble(3, 0, () -> 0);
        bkEnsemble.start();

        // start pulsar service
        config = new ServiceConfiguration();
        config.setZookeeperServers("127.0.0.1" + ":" + bkEnsemble.getZookeeperPort());
        config.setAdvertisedAddress("localhost");
        config.setWebServicePort(Optional.ofNullable(0));
        config.setClusterName("usc");
        config.setBrokerServicePort(Optional.ofNullable(0));
        config.setAuthorizationEnabled(false);
        config.setAuthenticationEnabled(false);
        config.setBacklogQuotaCheckIntervalInSeconds(TIME_TO_CHECK_BACKLOG_QUOTA);
        config.setManagedLedgerMaxEntriesPerLedger(MAX_ENTRIES_PER_LEDGER);
        config.setManagedLedgerMinLedgerRolloverTimeMinutes(0);
        config.setAllowAutoTopicCreationType("non-partitioned");

        pulsar = new PulsarService(config);
        pulsar.start();

        adminUrl = new URL("http://127.0.0.1" + ":" + pulsar.getListenPortHTTP().get());
        admin = PulsarAdmin.builder().serviceHttpUrl(adminUrl.toString()).build();

        admin.clusters().createCluster("usc", new ClusterData(adminUrl.toString()));
        admin.tenants().createTenant("prop",
                new TenantInfo(Sets.newHashSet("appid1"), Sets.newHashSet("usc")));
        admin.namespaces().createNamespace("prop/ns-quota");
        admin.namespaces().setNamespaceReplicationClusters("prop/ns-quota", Sets.newHashSet("usc"));
        admin.namespaces().createNamespace("prop/quotahold");
        admin.namespaces().setNamespaceReplicationClusters("prop/quotahold", Sets.newHashSet("usc"));
        admin.namespaces().createNamespace("prop/quotaholdasync");
        admin.namespaces().setNamespaceReplicationClusters("prop/quotaholdasync", Sets.newHashSet("usc"));
    } catch (Throwable t) {
        LOG.error("Error setting up broker test", t);
        fail("Broker test setup failed");
    }
}