Search in sources :

Example 1 with AuthenticationState

use of org.apache.pulsar.broker.authentication.AuthenticationState in project starlight-for-kafka by datastax.

the class PlainSaslServer method evaluateResponse.

@Override
public byte[] evaluateResponse(byte[] response) throws SaslException {
    SaslAuth saslAuth;
    try {
        saslAuth = SaslUtils.parseSaslAuthBytes(response);
    } catch (IOException e) {
        throw new SaslException(e.getMessage());
    }
    username = saslAuth.getUsername();
    AuthenticationProvider authenticationProvider = authenticationService.getAuthenticationProvider(saslAuth.getAuthMethod());
    if (authenticationProvider == null) {
        throw new SaslException("No AuthenticationProvider found for method " + saslAuth.getAuthMethod());
    }
    try {
        final AuthenticationState authState = authenticationProvider.newAuthState(AuthData.of(saslAuth.getAuthData().getBytes(StandardCharsets.UTF_8)), null, null);
        final String role = authState.getAuthRole();
        if (StringUtils.isEmpty(role)) {
            throw new AuthenticationException("Role cannot be empty.");
        }
        if (proxyRoles != null && proxyRoles.contains(authState.getAuthRole())) {
            // the Proxy passes the OriginalPrincipal as "username"
            authorizationId = saslAuth.getUsername();
            // PULSAR TENANT
            username = null;
            if (authorizationId.contains("/")) {
                // the proxy uses username/originalPrincipal as "username"
                int lastSlash = authorizationId.lastIndexOf('/');
                username = authorizationId.substring(lastSlash + 1);
                authorizationId = authorizationId.substring(0, lastSlash);
            }
            log.info("Authenticated Proxy role {} as user role {} tenant (username) {}", authState.getAuthRole(), authorizationId, username);
            if (proxyRoles.contains(authorizationId)) {
                throw new SaslException("The proxy (with role " + authState.getAuthRole() + ") tried to forward another proxy user (with role " + authorizationId + ")");
            }
        } else {
            authorizationId = authState.getAuthRole();
            log.info("Authenticated User {} tenant (username) {}", authorizationId, username);
        }
        complete = true;
        return new byte[0];
    } catch (AuthenticationException e) {
        throw new SaslException(e.getMessage());
    }
}
Also used : SaslAuth(io.streamnative.pulsar.handlers.kop.SaslAuth) AuthenticationException(javax.naming.AuthenticationException) AuthenticationProvider(org.apache.pulsar.broker.authentication.AuthenticationProvider) IOException(java.io.IOException) SaslException(javax.security.sasl.SaslException) AuthenticationState(org.apache.pulsar.broker.authentication.AuthenticationState)

Example 2 with AuthenticationState

use of org.apache.pulsar.broker.authentication.AuthenticationState in project pulsar by apache.

the class AuthenticationFilter method doFilter.

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if (!isSaslRequest(httpRequest)) {
            // not sasl type, return role directly.
            String authMethodName = httpRequest.getHeader(PULSAR_AUTH_METHOD_NAME);
            String role;
            if (authMethodName != null && authenticationService.getAuthenticationProvider(authMethodName) != null) {
                AuthenticationState authenticationState = authenticationService.getAuthenticationProvider(authMethodName).newHttpAuthState(httpRequest);
                request.setAttribute(AuthenticatedDataAttributeName, authenticationState.getAuthDataSource());
                role = authenticationService.authenticateHttpRequest((HttpServletRequest) request, authenticationState.getAuthDataSource());
            } else {
                request.setAttribute(AuthenticatedDataAttributeName, new AuthenticationDataHttps((HttpServletRequest) request));
                role = authenticationService.authenticateHttpRequest((HttpServletRequest) request);
            }
            request.setAttribute(AuthenticatedRoleAttributeName, role);
            if (LOG.isDebugEnabled()) {
                LOG.debug("[{}] Authenticated HTTP request with role {}", request.getRemoteAddr(), role);
            }
            chain.doFilter(request, response);
            return;
        }
        boolean doFilter = authenticationService.getAuthenticationProvider(SaslConstants.AUTH_METHOD_NAME).authenticateHttpRequest(httpRequest, httpResponse);
        if (doFilter) {
            chain.doFilter(request, response);
        }
    } catch (Exception e) {
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        httpResponse.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Authentication required");
        if (e instanceof AuthenticationException) {
            LOG.warn("[{}] Failed to authenticate HTTP request: {}", request.getRemoteAddr(), e.getMessage());
        } else {
            LOG.error("[{}] Error performing authentication for HTTP", request.getRemoteAddr(), e);
        }
        return;
    }
}
Also used : HttpServletRequest(javax.servlet.http.HttpServletRequest) AuthenticationException(javax.naming.AuthenticationException) HttpServletResponse(javax.servlet.http.HttpServletResponse) AuthenticationDataHttps(org.apache.pulsar.broker.authentication.AuthenticationDataHttps) ServletException(javax.servlet.ServletException) IOException(java.io.IOException) AuthenticationException(javax.naming.AuthenticationException) AuthenticationState(org.apache.pulsar.broker.authentication.AuthenticationState)

Example 3 with AuthenticationState

use of org.apache.pulsar.broker.authentication.AuthenticationState in project pulsar by apache.

the class ServerCnx method refreshAuthenticationCredentials.

public void refreshAuthenticationCredentials() {
    AuthenticationState authState = this.originalAuthState != null ? originalAuthState : this.authState;
    if (authState == null) {
        // Authentication is disabled or there's no local state to refresh
        return;
    } else if (getState() != State.Connected || !isActive) {
        // Connection is either still being established or already closed.
        return;
    } else if (!authState.isExpired()) {
        // Credentials are still valid. Nothing to do at this point
        return;
    } else if (originalPrincipal != null && originalAuthState == null) {
        log.info("[{}] Cannot revalidate user credential when using proxy and" + " not forwarding the credentials. Closing connection", remoteAddress);
        return;
    }
    ctx.executor().execute(SafeRun.safeRun(() -> {
        log.info("[{}] Refreshing authentication credentials for originalPrincipal {} and authRole {}", remoteAddress, originalPrincipal, this.authRole);
        if (!supportsAuthenticationRefresh()) {
            log.warn("[{}] Closing connection because client doesn't support auth credentials refresh", remoteAddress);
            ctx.close();
            return;
        }
        if (pendingAuthChallengeResponse) {
            log.warn("[{}] Closing connection after timeout on refreshing auth credentials", remoteAddress);
            ctx.close();
            return;
        }
        try {
            AuthData brokerData = authState.refreshAuthentication();
            ctx.writeAndFlush(Commands.newAuthChallenge(authMethod, brokerData, getRemoteEndpointProtocolVersion()));
            if (log.isDebugEnabled()) {
                log.debug("[{}] Sent auth challenge to client to refresh credentials with method: {}.", remoteAddress, authMethod);
            }
            pendingAuthChallengeResponse = true;
        } catch (AuthenticationException e) {
            log.warn("[{}] Failed to refresh authentication: {}", remoteAddress, e);
            ctx.close();
        }
    }));
}
Also used : AuthData(org.apache.pulsar.common.api.AuthData) AuthenticationException(javax.naming.AuthenticationException) AuthenticationState(org.apache.pulsar.broker.authentication.AuthenticationState)

Example 4 with AuthenticationState

use of org.apache.pulsar.broker.authentication.AuthenticationState in project pulsar by apache.

the class ServerCnxTest method testConnectCommandWithAuthenticationPositive.

@Test(timeOut = 30000)
public void testConnectCommandWithAuthenticationPositive() throws Exception {
    AuthenticationService authenticationService = mock(AuthenticationService.class);
    AuthenticationProvider authenticationProvider = mock(AuthenticationProvider.class);
    AuthenticationState authenticationState = mock(AuthenticationState.class);
    AuthenticationDataSource authenticationDataSource = mock(AuthenticationDataSource.class);
    AuthData authData = AuthData.of(null);
    doReturn(authenticationService).when(brokerService).getAuthenticationService();
    doReturn(authenticationProvider).when(authenticationService).getAuthenticationProvider(Mockito.anyString());
    doReturn(authenticationState).when(authenticationProvider).newAuthState(Mockito.any(), Mockito.any(), Mockito.any());
    doReturn(authData).when(authenticationState).authenticate(authData);
    doReturn(true).when(authenticationState).isComplete();
    doReturn("appid1").when(authenticationState).getAuthRole();
    doReturn(true).when(brokerService).isAuthenticationEnabled();
    resetChannel();
    assertTrue(channel.isActive());
    assertEquals(serverCnx.getState(), State.Start);
    // test server response to CONNECT
    ByteBuf clientCommand = Commands.newConnect("none", "", null);
    channel.writeInbound(clientCommand);
    assertEquals(serverCnx.getState(), State.Connected);
    assertTrue(getResponse() instanceof CommandConnected);
    channel.finish();
}
Also used : AuthData(org.apache.pulsar.common.api.AuthData) CommandConnected(org.apache.pulsar.common.api.proto.CommandConnected) AuthenticationProvider(org.apache.pulsar.broker.authentication.AuthenticationProvider) AuthenticationDataSource(org.apache.pulsar.broker.authentication.AuthenticationDataSource) ByteBuf(io.netty.buffer.ByteBuf) AuthenticationService(org.apache.pulsar.broker.authentication.AuthenticationService) AuthenticationState(org.apache.pulsar.broker.authentication.AuthenticationState) Test(org.testng.annotations.Test)

Example 5 with AuthenticationState

use of org.apache.pulsar.broker.authentication.AuthenticationState in project kop by streamnative.

the class OauthValidatorCallbackHandler method handleCallback.

private void handleCallback(OAuthBearerValidatorCallback callback) {
    if (callback.tokenValue() == null) {
        throw new IllegalArgumentException("Callback has null token value!");
    }
    if (SaslAuthenticator.getAuthenticationService() == null) {
        throw new IllegalStateException("AuthenticationService is null during token validation");
    }
    final AuthenticationProvider authenticationProvider = SaslAuthenticator.getAuthenticationService().getAuthenticationProvider(config.getValidateMethod());
    if (authenticationProvider == null) {
        throw new IllegalStateException("No AuthenticationProvider found for method " + config.getValidateMethod());
    }
    final String token = callback.tokenValue();
    try {
        final AuthenticationState authState = authenticationProvider.newAuthState(AuthData.of(token.getBytes(StandardCharsets.UTF_8)), null, null);
        final String role = authState.getAuthRole();
        callback.token(new OAuthBearerToken() {

            @Override
            public String value() {
                return token;
            }

            @Override
            public Set<String> scope() {
                return null;
            }

            @Override
            public long lifetimeMs() {
                // TODO: convert "exp" claim to ms.
                return Long.MAX_VALUE;
            }

            @Override
            public String principalName() {
                return role;
            }

            @Override
            public Long startTimeMs() {
                // TODO: convert "iat" claim to ms.
                return Long.MAX_VALUE;
            }
        });
    } catch (AuthenticationException e) {
        throw new OAuthBearerIllegalTokenException(OAuthBearerValidationResult.newFailure(e.getMessage()));
    }
}
Also used : Set(java.util.Set) AuthenticationException(javax.naming.AuthenticationException) OAuthBearerToken(org.apache.kafka.common.security.oauthbearer.OAuthBearerToken) AuthenticationProvider(org.apache.pulsar.broker.authentication.AuthenticationProvider) OAuthBearerIllegalTokenException(org.apache.kafka.common.security.oauthbearer.internals.unsecured.OAuthBearerIllegalTokenException) AuthenticationState(org.apache.pulsar.broker.authentication.AuthenticationState)

Aggregations

AuthenticationState (org.apache.pulsar.broker.authentication.AuthenticationState)21 AuthData (org.apache.pulsar.common.api.AuthData)11 AuthenticationException (javax.naming.AuthenticationException)10 AuthenticationProvider (org.apache.pulsar.broker.authentication.AuthenticationProvider)9 IOException (java.io.IOException)8 AuthenticationDataHttps (org.apache.pulsar.broker.authentication.AuthenticationDataHttps)6 AuthenticationDataSource (org.apache.pulsar.broker.authentication.AuthenticationDataSource)6 AuthenticationService (org.apache.pulsar.broker.authentication.AuthenticationService)5 ByteBuf (io.netty.buffer.ByteBuf)3 ServletException (javax.servlet.ServletException)3 HttpServletRequest (javax.servlet.http.HttpServletRequest)3 HttpServletResponse (javax.servlet.http.HttpServletResponse)3 AuthenticationException (org.apache.pulsar.client.api.PulsarClientException.AuthenticationException)3 AuthorizationException (org.apache.pulsar.client.api.PulsarClientException.AuthorizationException)3 ConsumerBusyException (org.apache.pulsar.client.api.PulsarClientException.ConsumerBusyException)3 IncompatibleSchemaException (org.apache.pulsar.client.api.PulsarClientException.IncompatibleSchemaException)3 NotFoundException (org.apache.pulsar.client.api.PulsarClientException.NotFoundException)3 ProducerBlockedQuotaExceededException (org.apache.pulsar.client.api.PulsarClientException.ProducerBlockedQuotaExceededException)3 ProducerBusyException (org.apache.pulsar.client.api.PulsarClientException.ProducerBusyException)3 ProducerFencedException (org.apache.pulsar.client.api.PulsarClientException.ProducerFencedException)3