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());
}
}
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;
}
}
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();
}
}));
}
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();
}
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()));
}
}
Aggregations