Search in sources :

Example 1 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class HttpManagement method onClose.

@Override
protected ListenableFuture<Void> onClose() {
    getBroker().removeChangeListener(_brokerChangeListener);
    if (_server != null) {
        try {
            logOperationalShutdownMessage();
            _server.stop();
        } catch (Exception e) {
            throw new ServerScopedRuntimeException("Failed to stop HTTP management", e);
        }
    }
    if (_jettyServerExecutor != null) {
        _jettyServerExecutor.shutdown();
    }
    getBroker().getEventLogger().message(ManagementConsoleMessages.STOPPED(OPERATIONAL_LOGGING_NAME));
    return Futures.immediateFuture(null);
}
Also used : IOException(java.io.IOException) PortBindFailureException(org.apache.qpid.server.transport.PortBindFailureException) BindException(java.net.BindException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) IllegalConfigurationException(org.apache.qpid.server.configuration.IllegalConfigurationException) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Example 2 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class LDAPSSLSocketFactoryGenerator method setSslSocketFactoryFieldByReflection.

private static void setSslSocketFactoryFieldByReflection(Class<? extends AbstractLDAPSSLSocketFactory> clazz, String fieldName, SSLSocketFactory sslSocketFactory) {
    String exceptionMessage = "Unexpected error setting generated static field " + fieldName + "on generated class " + clazz.getName();
    try {
        Field declaredField = clazz.getDeclaredField(fieldName);
        boolean accessible = declaredField.isAccessible();
        try {
            declaredField.setAccessible(true);
            declaredField.set(null, sslSocketFactory);
        } finally {
            declaredField.setAccessible(accessible);
        }
    } catch (IllegalArgumentException e) {
        throw new ServerScopedRuntimeException(exceptionMessage, e);
    } catch (IllegalAccessException e) {
        throw new ServerScopedRuntimeException(exceptionMessage, e);
    } catch (NoSuchFieldException e) {
        throw new ServerScopedRuntimeException(exceptionMessage, e);
    } catch (SecurityException e) {
        throw new ServerScopedRuntimeException(exceptionMessage, e);
    }
}
Also used : Field(java.lang.reflect.Field) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Example 3 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class OAuth2AuthenticationProviderImpl method authenticateViaAuthorizationCode.

@Override
public AuthenticationResult authenticateViaAuthorizationCode(final String authorizationCode, final String redirectUri, NamedAddressSpace addressSpace) {
    URL tokenEndpoint;
    HttpURLConnection connection;
    byte[] body;
    try {
        tokenEndpoint = getTokenEndpointURI(addressSpace).toURL();
        ConnectionBuilder connectionBuilder = new ConnectionBuilder(tokenEndpoint);
        connectionBuilder.setConnectTimeout(_connectTimeout).setReadTimeout(_readTimeout);
        if (getTrustStore() != null) {
            try {
                connectionBuilder.setTrustMangers(getTrustStore().getTrustManagers());
            } catch (GeneralSecurityException e) {
                throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
            }
        }
        connectionBuilder.setTlsProtocolWhiteList(getTlsProtocolWhiteList()).setTlsProtocolBlackList(getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(getTlsCipherSuiteBlackList());
        LOGGER.debug("About to call token endpoint '{}'", tokenEndpoint);
        connection = connectionBuilder.build();
        // makes sure to use POST
        connection.setDoOutput(true);
        connection.setRequestProperty("Accept-Charset", UTF_8.name());
        connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_8.name());
        connection.setRequestProperty("Accept", "application/json");
        if (getTokenEndpointNeedsAuth()) {
            String encoded = DatatypeConverter.printBase64Binary((getClientId() + ":" + getClientSecret()).getBytes(UTF_8));
            connection.setRequestProperty("Authorization", "Basic " + encoded);
        }
        Map<String, String> requestBody = new HashMap<>();
        requestBody.put("code", authorizationCode);
        requestBody.put("client_id", getClientId());
        requestBody.put("client_secret", getClientSecret());
        requestBody.put("redirect_uri", redirectUri);
        requestBody.put("grant_type", "authorization_code");
        requestBody.put("response_type", "token");
        body = OAuth2Utils.buildRequestQuery(requestBody).getBytes(UTF_8);
        connection.connect();
        try (OutputStream output = connection.getOutputStream()) {
            output.write(body);
        }
        try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
            final int responseCode = connection.getResponseCode();
            LOGGER.debug("Call to token endpoint '{}' complete, response code : {}", tokenEndpoint, responseCode);
            Map<String, Object> responseMap = _objectMapper.readValue(input, Map.class);
            if (responseCode != 200 || responseMap.containsKey("error")) {
                IllegalStateException e = new IllegalStateException(String.format("Token endpoint failed, response code %d, error '%s', description '%s'", responseCode, responseMap.get("error"), responseMap.get("error_description")));
                LOGGER.error(e.getMessage());
                return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
            }
            Object accessTokenObject = responseMap.get("access_token");
            if (accessTokenObject == null) {
                IllegalStateException e = new IllegalStateException("Token endpoint response did not include 'access_token'");
                LOGGER.error("Unexpected token endpoint response", e);
                return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
            }
            String accessToken = String.valueOf(accessTokenObject);
            return authenticateViaAccessToken(accessToken, addressSpace);
        } catch (JsonProcessingException e) {
            IllegalStateException ise = new IllegalStateException(String.format("Token endpoint '%s' did not return json", tokenEndpoint), e);
            LOGGER.error("Unexpected token endpoint response", e);
            return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, ise);
        }
    } catch (IOException e) {
        LOGGER.error("Call to token endpoint failed", e);
        return new AuthenticationResult(AuthenticationResult.AuthenticationStatus.ERROR, e);
    }
}
Also used : HashMap(java.util.HashMap) InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) OutputStream(java.io.OutputStream) ConnectionBuilder(org.apache.qpid.server.util.ConnectionBuilder) IOException(java.io.IOException) URL(java.net.URL) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) AuthenticationResult(org.apache.qpid.server.security.auth.AuthenticationResult) HttpURLConnection(java.net.HttpURLConnection) ConfiguredObject(org.apache.qpid.server.model.ConfiguredObject) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 4 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class OAuth2Utils method buildRequestQuery.

public static String buildRequestQuery(final Map<String, String> requestBodyParameters) {
    try {
        final String charset = StandardCharsets.UTF_8.name();
        StringBuilder bodyBuilder = new StringBuilder();
        Iterator<Map.Entry<String, String>> iterator = requestBodyParameters.entrySet().iterator();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = iterator.next();
            bodyBuilder.append(URLEncoder.encode(entry.getKey(), charset));
            bodyBuilder.append("=");
            bodyBuilder.append(URLEncoder.encode(entry.getValue(), charset));
            if (iterator.hasNext()) {
                bodyBuilder.append("&");
            }
        }
        return bodyBuilder.toString();
    } catch (UnsupportedEncodingException e) {
        throw new ServerScopedRuntimeException("Failed to encode as UTF-8", e);
    }
}
Also used : UnsupportedEncodingException(java.io.UnsupportedEncodingException) Map(java.util.Map) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException)

Example 5 with ServerScopedRuntimeException

use of org.apache.qpid.server.util.ServerScopedRuntimeException in project qpid-broker-j by apache.

the class CloudFoundryOAuth2IdentityResolverService method getUserPrincipal.

@Override
public Principal getUserPrincipal(final OAuth2AuthenticationProvider<?> authenticationProvider, final String accessToken, final NamedAddressSpace addressSpace) throws IOException, IdentityResolverException {
    URL checkTokenEndpoint = authenticationProvider.getIdentityResolverEndpointURI(addressSpace).toURL();
    TrustStore trustStore = authenticationProvider.getTrustStore();
    String clientId = authenticationProvider.getClientId();
    String clientSecret = authenticationProvider.getClientSecret();
    ConnectionBuilder connectionBuilder = new ConnectionBuilder(checkTokenEndpoint);
    connectionBuilder.setConnectTimeout(authenticationProvider.getConnectTimeout()).setReadTimeout(authenticationProvider.getReadTimeout());
    if (trustStore != null) {
        try {
            connectionBuilder.setTrustMangers(trustStore.getTrustManagers());
        } catch (GeneralSecurityException e) {
            throw new ServerScopedRuntimeException("Cannot initialise TLS", e);
        }
    }
    connectionBuilder.setTlsProtocolWhiteList(authenticationProvider.getTlsProtocolWhiteList()).setTlsProtocolBlackList(authenticationProvider.getTlsProtocolBlackList()).setTlsCipherSuiteWhiteList(authenticationProvider.getTlsCipherSuiteWhiteList()).setTlsCipherSuiteBlackList(authenticationProvider.getTlsCipherSuiteBlackList());
    LOGGER.debug("About to call identity service '{}'", checkTokenEndpoint);
    HttpURLConnection connection = connectionBuilder.build();
    // makes sure to use POST
    connection.setDoOutput(true);
    connection.setRequestProperty("Accept-Charset", UTF_8.name());
    connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + UTF_8.name());
    connection.setRequestProperty("Accept", "application/json");
    String encoded = DatatypeConverter.printBase64Binary((clientId + ":" + clientSecret).getBytes(UTF_8));
    connection.setRequestProperty("Authorization", "Basic " + encoded);
    final Map<String, String> requestParameters = Collections.singletonMap("token", accessToken);
    connection.connect();
    try (OutputStream output = connection.getOutputStream()) {
        output.write(OAuth2Utils.buildRequestQuery(requestParameters).getBytes(UTF_8));
        output.close();
        try (InputStream input = OAuth2Utils.getResponseStream(connection)) {
            int responseCode = connection.getResponseCode();
            LOGGER.debug("Call to identity service '{}' complete, response code : {}", checkTokenEndpoint, responseCode);
            Map<String, String> responseMap = null;
            try {
                responseMap = _objectMapper.readValue(input, Map.class);
            } catch (JsonProcessingException e) {
                throw new IOException(String.format("Identity resolver '%s' did not return json", checkTokenEndpoint), e);
            }
            if (responseCode != 200) {
                throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response code %d, error '%s', description '%s'", checkTokenEndpoint, responseCode, responseMap.get("error"), responseMap.get("error_description")));
            }
            final String userName = responseMap.get("user_name");
            if (userName == null) {
                throw new IdentityResolverException(String.format("Identity resolver '%s' failed, response did not include 'user_name'", checkTokenEndpoint));
            }
            return new UsernamePrincipal(userName, authenticationProvider);
        }
    }
}
Also used : InputStream(java.io.InputStream) GeneralSecurityException(java.security.GeneralSecurityException) OutputStream(java.io.OutputStream) IdentityResolverException(org.apache.qpid.server.security.auth.manager.oauth2.IdentityResolverException) ConnectionBuilder(org.apache.qpid.server.util.ConnectionBuilder) TrustStore(org.apache.qpid.server.model.TrustStore) IOException(java.io.IOException) URL(java.net.URL) ServerScopedRuntimeException(org.apache.qpid.server.util.ServerScopedRuntimeException) UsernamePrincipal(org.apache.qpid.server.security.auth.UsernamePrincipal) HttpURLConnection(java.net.HttpURLConnection) Map(java.util.Map) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Aggregations

ServerScopedRuntimeException (org.apache.qpid.server.util.ServerScopedRuntimeException)45 IOException (java.io.IOException)17 GeneralSecurityException (java.security.GeneralSecurityException)10 Map (java.util.Map)10 ConnectionScopedRuntimeException (org.apache.qpid.server.util.ConnectionScopedRuntimeException)10 JsonProcessingException (com.fasterxml.jackson.core.JsonProcessingException)9 URL (java.net.URL)9 InputStream (java.io.InputStream)8 HttpURLConnection (java.net.HttpURLConnection)8 ConnectionBuilder (org.apache.qpid.server.util.ConnectionBuilder)8 InvocationTargetException (java.lang.reflect.InvocationTargetException)7 IllegalConfigurationException (org.apache.qpid.server.configuration.IllegalConfigurationException)6 TrustStore (org.apache.qpid.server.model.TrustStore)6 UsernamePrincipal (org.apache.qpid.server.security.auth.UsernamePrincipal)6 IdentityResolverException (org.apache.qpid.server.security.auth.manager.oauth2.IdentityResolverException)6 Field (java.lang.reflect.Field)5 Method (java.lang.reflect.Method)4 ArrayList (java.util.ArrayList)4 UnsupportedEncodingException (java.io.UnsupportedEncodingException)3 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)3