Search in sources :

Example 1 with AuthenticationDataSource

use of org.apache.pulsar.broker.authentication.AuthenticationDataSource in project incubator-pulsar by apache.

the class AuthenticationProviderAthenzTest method testAuthenticateUnsignedToken.

@Test
public void testAuthenticateUnsignedToken() throws Exception {
    List<String> roles = new ArrayList<String>() {

        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "test_provider", roles).principal("test_app").build();
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getUnsignedToken(), new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    try {
        provider.authenticate(authData);
        fail("Unsigned token should not be authenticated");
    } catch (AuthenticationException e) {
    // OK, expected
    }
}
Also used : AuthenticationDataCommand(org.apache.pulsar.broker.authentication.AuthenticationDataCommand) AuthenticationException(javax.naming.AuthenticationException) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) RoleToken(com.yahoo.athenz.auth.token.RoleToken) Test(org.testng.annotations.Test)

Example 2 with AuthenticationDataSource

use of org.apache.pulsar.broker.authentication.AuthenticationDataSource in project incubator-pulsar by apache.

the class PulsarAuthorizationProvider method canConsumeAsync.

/**
 * Check if the specified role has permission to receive messages from the specified fully qualified topic
 * name.
 *
 * @param topicName
 *            the fully qualified topic name associated with the topic.
 * @param role
 *            the app id used to receive messages from the topic.
 * @param subscription
 *            the subscription name defined by the client
 */
@Override
public CompletableFuture<Boolean> canConsumeAsync(TopicName topicName, String role, AuthenticationDataSource authenticationData, String subscription) {
    CompletableFuture<Boolean> permissionFuture = new CompletableFuture<>();
    try {
        configCache.policiesCache().getAsync(POLICY_ROOT + topicName.getNamespace()).thenAccept(policies -> {
            if (!policies.isPresent()) {
                if (log.isDebugEnabled()) {
                    log.debug("Policies node couldn't be found for topic : {}", topicName);
                }
            } else {
                if (isNotBlank(subscription) && !isSuperUser(role)) {
                    switch(policies.get().subscription_auth_mode) {
                        case Prefix:
                            if (!subscription.startsWith(role)) {
                                PulsarServerException ex = new PulsarServerException(String.format("Failed to create consumer - The subscription name needs to be prefixed by the authentication role, like %s-xxxx for topic: %s", role, topicName));
                                permissionFuture.completeExceptionally(ex);
                                return;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
            checkAuthorization(topicName, role, AuthAction.consume).thenAccept(isAuthorized -> {
                permissionFuture.complete(isAuthorized);
            });
        }).exceptionally(ex -> {
            log.warn("Client with Role - {} failed to get permissions for topic - {}. {}", role, topicName, ex.getMessage());
            permissionFuture.completeExceptionally(ex);
            return null;
        });
    } catch (Exception e) {
        log.warn("Client  with Role - {} failed to get permissions for topic - {}. {}", role, topicName, e.getMessage());
        permissionFuture.completeExceptionally(e);
    }
    return permissionFuture;
}
Also used : ZooKeeper(org.apache.zookeeper.ZooKeeper) TopicName(org.apache.pulsar.common.naming.TopicName) Logger(org.slf4j.Logger) KeeperException(org.apache.zookeeper.KeeperException) ServiceConfiguration(org.apache.pulsar.broker.ServiceConfiguration) Preconditions.checkNotNull(com.google.common.base.Preconditions.checkNotNull) ObjectMapperFactory.getThreadLocal(org.apache.pulsar.common.util.ObjectMapperFactory.getThreadLocal) LoggerFactory(org.slf4j.LoggerFactory) Set(java.util.Set) IOException(java.io.IOException) CompletableFuture(java.util.concurrent.CompletableFuture) ConfigurationCacheService(org.apache.pulsar.broker.cache.ConfigurationCacheService) Stat(org.apache.zookeeper.data.Stat) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) States(org.apache.zookeeper.ZooKeeper.States) Policies(org.apache.pulsar.common.policies.data.Policies) StringUtils.isNotBlank(org.apache.commons.lang3.StringUtils.isNotBlank) POLICIES(org.apache.pulsar.broker.cache.ConfigurationCacheService.POLICIES) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) AuthAction(org.apache.pulsar.common.policies.data.AuthAction) ZooKeeperCache(org.apache.pulsar.zookeeper.ZooKeeperCache) Map(java.util.Map) NamespaceName(org.apache.pulsar.common.naming.NamespaceName) PulsarServerException(org.apache.pulsar.broker.PulsarServerException) CompletableFuture(java.util.concurrent.CompletableFuture) KeeperException(org.apache.zookeeper.KeeperException) IOException(java.io.IOException) PulsarServerException(org.apache.pulsar.broker.PulsarServerException)

Example 3 with AuthenticationDataSource

use of org.apache.pulsar.broker.authentication.AuthenticationDataSource in project incubator-pulsar by apache.

the class AuthenticationProviderAthenzTest method testAuthenticateSignedTokenWithDifferentDomain.

@Test
public void testAuthenticateSignedTokenWithDifferentDomain() throws Exception {
    List<String> roles = new ArrayList<String>() {

        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "invalid", roles).principal("test_app").build();
    String privateKey = new String(Files.readAllBytes(Paths.get("./src/test/resources/zts_private.pem")));
    token.sign(privateKey);
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getSignedToken(), new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    try {
        provider.authenticate(authData);
        fail("Token which has different domain should not be authenticated");
    } catch (AuthenticationException e) {
    // OK, expected
    }
}
Also used : AuthenticationDataCommand(org.apache.pulsar.broker.authentication.AuthenticationDataCommand) AuthenticationException(javax.naming.AuthenticationException) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) RoleToken(com.yahoo.athenz.auth.token.RoleToken) Test(org.testng.annotations.Test)

Example 4 with AuthenticationDataSource

use of org.apache.pulsar.broker.authentication.AuthenticationDataSource in project incubator-pulsar by apache.

the class AuthenticationProviderAthenzTest method testAuthenticateSignedToken.

@Test
public void testAuthenticateSignedToken() throws Exception {
    List<String> roles = new ArrayList<String>() {

        {
            add("test_role");
        }
    };
    RoleToken token = new RoleToken.Builder("Z1", "test_provider", roles).principal("test_app").build();
    String privateKey = new String(Files.readAllBytes(Paths.get("./src/test/resources/zts_private.pem")));
    token.sign(privateKey);
    AuthenticationDataSource authData = new AuthenticationDataCommand(token.getSignedToken(), new InetSocketAddress("localhost", PortManager.nextFreePort()), null);
    assertEquals(provider.authenticate(authData), "test_app");
}
Also used : AuthenticationDataCommand(org.apache.pulsar.broker.authentication.AuthenticationDataCommand) InetSocketAddress(java.net.InetSocketAddress) ArrayList(java.util.ArrayList) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) RoleToken(com.yahoo.athenz.auth.token.RoleToken) Test(org.testng.annotations.Test)

Example 5 with AuthenticationDataSource

use of org.apache.pulsar.broker.authentication.AuthenticationDataSource in project incubator-pulsar by apache.

the class AbstractWebSocketHandler method checkAuth.

protected boolean checkAuth(ServletUpgradeResponse response) {
    String authRole = "<none>";
    AuthenticationDataSource authenticationData = new AuthenticationDataHttps(request);
    if (service.isAuthenticationEnabled()) {
        try {
            authRole = service.getAuthenticationService().authenticateHttpRequest(request);
            log.info("[{}:{}] Authenticated WebSocket client {} on topic {}", request.getRemoteAddr(), request.getRemotePort(), authRole, topic);
        } catch (AuthenticationException e) {
            log.warn("[{}:{}] Failed to authenticated WebSocket client {} on topic {}: {}", request.getRemoteAddr(), request.getRemotePort(), authRole, topic, e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Failed to authenticate");
            } catch (IOException e1) {
                log.warn("[{}:{}] Failed to send error: {}", request.getRemoteAddr(), request.getRemotePort(), e1.getMessage(), e1);
            }
            return false;
        }
    }
    if (service.isAuthorizationEnabled()) {
        try {
            if (!isAuthorized(authRole, authenticationData)) {
                log.warn("[{}:{}] WebSocket Client [{}] is not authorized on topic {}", request.getRemoteAddr(), request.getRemotePort(), authRole, topic);
                response.sendError(HttpServletResponse.SC_FORBIDDEN, "Not authorized");
                return false;
            }
        } catch (Exception e) {
            log.warn("[{}:{}] Got an exception when authorizing WebSocket client {} on topic {} on: {}", request.getRemoteAddr(), request.getRemotePort(), authRole, topic, e.getMessage());
            try {
                response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "Server error");
            } catch (IOException e1) {
                log.warn("[{}:{}] Failed to send error: {}", request.getRemoteAddr(), request.getRemotePort(), e1.getMessage(), e1);
            }
            return false;
        }
    }
    return true;
}
Also used : AuthenticationException(javax.naming.AuthenticationException) IOException(java.io.IOException) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) AuthenticationDataHttps(org.apache.pulsar.broker.authentication.AuthenticationDataHttps) IOException(java.io.IOException) AuthenticationException(javax.naming.AuthenticationException)

Aggregations

AuthenticationDataSource (org.apache.pulsar.broker.authentication.AuthenticationDataSource)6 RoleToken (com.yahoo.athenz.auth.token.RoleToken)3 InetSocketAddress (java.net.InetSocketAddress)3 ArrayList (java.util.ArrayList)3 AuthenticationException (javax.naming.AuthenticationException)3 AuthenticationDataCommand (org.apache.pulsar.broker.authentication.AuthenticationDataCommand)3 Test (org.testng.annotations.Test)3 Preconditions.checkNotNull (com.google.common.base.Preconditions.checkNotNull)2 IOException (java.io.IOException)2 CompletableFuture (java.util.concurrent.CompletableFuture)2 TopicName (org.apache.pulsar.common.naming.TopicName)2 Logger (org.slf4j.Logger)2 LoggerFactory (org.slf4j.LoggerFactory)2 StringUtils (dlshade.org.apache.commons.lang3.StringUtils)1 ByteBuf (io.netty.buffer.ByteBuf)1 ApiResponse (io.swagger.annotations.ApiResponse)1 ApiResponses (io.swagger.annotations.ApiResponses)1 URI (java.net.URI)1 URISyntaxException (java.net.URISyntaxException)1 Map (java.util.Map)1