Search in sources :

Example 1 with AuthorizationException

use of org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException in project nifi-minifi by apache.

the class DelegatingConfigurationProvider method getDelegateConnection.

protected HttpURLConnection getDelegateConnection(String contentType, Map<String, List<String>> parameters) throws ConfigurationProviderException {
    StringBuilder queryStringBuilder = new StringBuilder();
    try {
        parameters.entrySet().stream().sorted(Comparator.comparing(Map.Entry::getKey)).forEachOrdered(e -> e.getValue().stream().sorted().forEachOrdered(v -> {
            try {
                queryStringBuilder.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=").append(URLEncoder.encode(v, "UTF-8"));
            } catch (UnsupportedEncodingException ex) {
                throw new ConfigurationProviderException("Unsupported encoding.", ex).wrap();
            }
            queryStringBuilder.append("&");
        }));
    } catch (ConfigurationProviderException.Wrapper e) {
        throw e.unwrap();
    }
    String url = "/c2/config";
    if (queryStringBuilder.length() > 0) {
        queryStringBuilder.setLength(queryStringBuilder.length() - 1);
        url = url + "?" + queryStringBuilder.toString();
    }
    HttpURLConnection httpURLConnection = httpConnector.get(url);
    httpURLConnection.setRequestProperty("Accepts", contentType);
    try {
        int responseCode;
        try {
            responseCode = httpURLConnection.getResponseCode();
        } catch (IOException e) {
            Matcher matcher = errorPattern.matcher(e.getMessage());
            if (matcher.matches()) {
                responseCode = Integer.parseInt(matcher.group(1));
            } else {
                throw e;
            }
        }
        if (responseCode >= 400) {
            String message = "";
            InputStream inputStream = httpURLConnection.getErrorStream();
            if (inputStream != null) {
                try {
                    message = IOUtils.toString(inputStream, StandardCharsets.UTF_8);
                } finally {
                    inputStream.close();
                }
            }
            if (responseCode == 400) {
                throw new InvalidParameterException(message);
            } else if (responseCode == 403) {
                throw new AuthorizationException("Got authorization exception from upstream server " + message);
            } else {
                throw new ConfigurationProviderException(message);
            }
        }
    } catch (IOException e) {
        throw new ConfigurationProviderException("Unable to get response code from upstream server.", e);
    }
    return httpURLConnection;
}
Also used : HttpURLConnection(java.net.HttpURLConnection) LoggerFactory(org.slf4j.LoggerFactory) ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) ConfigurationCacheFileInfo(org.apache.nifi.minifi.c2.api.cache.ConfigurationCacheFileInfo) AuthorizationException(org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException) GeneralSecurityException(java.security.GeneralSecurityException) Matcher(java.util.regex.Matcher) Map(java.util.Map) OutputStream(java.io.OutputStream) Logger(org.slf4j.Logger) ConfigurationProvider(org.apache.nifi.minifi.c2.api.ConfigurationProvider) WriteableConfiguration(org.apache.nifi.minifi.c2.api.cache.WriteableConfiguration) ObjectMapper(com.fasterxml.jackson.databind.ObjectMapper) HttpConnector(org.apache.nifi.minifi.c2.provider.util.HttpConnector) IOException(java.io.IOException) Configuration(org.apache.nifi.minifi.c2.api.Configuration) StandardCharsets(java.nio.charset.StandardCharsets) ConfigurationCache(org.apache.nifi.minifi.c2.api.cache.ConfigurationCache) IOUtils(org.apache.commons.io.IOUtils) URLEncoder(java.net.URLEncoder) List(java.util.List) InvalidParameterException(org.apache.nifi.minifi.c2.api.InvalidParameterException) Pattern(java.util.regex.Pattern) Comparator(java.util.Comparator) UnsupportedEncodingException(java.io.UnsupportedEncodingException) InputStream(java.io.InputStream) Matcher(java.util.regex.Matcher) AuthorizationException(org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException) InputStream(java.io.InputStream) UnsupportedEncodingException(java.io.UnsupportedEncodingException) IOException(java.io.IOException) ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) InvalidParameterException(org.apache.nifi.minifi.c2.api.InvalidParameterException) HttpURLConnection(java.net.HttpURLConnection)

Example 2 with AuthorizationException

use of org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException in project nifi-minifi by apache.

the class ConfigService method getConfig.

@GET
public Response getConfig(@Context HttpServletRequest request, @Context HttpHeaders httpHeaders, @Context UriInfo uriInfo) {
    try {
        authorizer.authorize(SecurityContextHolder.getContext().getAuthentication(), uriInfo);
    } catch (AuthorizationException e) {
        logger.warn(HttpRequestUtil.getClientString(request) + " not authorized to access " + uriInfo, e);
        return Response.status(403).build();
    }
    Map<String, List<String>> parameters = new HashMap<>();
    for (Map.Entry<String, List<String>> entry : uriInfo.getQueryParameters().entrySet()) {
        parameters.put(entry.getKey(), entry.getValue());
    }
    List<MediaType> acceptValues = httpHeaders.getAcceptableMediaTypes();
    boolean defaultAccept = false;
    if (acceptValues.size() == 0) {
        acceptValues = Arrays.asList(MediaType.WILDCARD_TYPE);
        defaultAccept = true;
    }
    if (logger.isDebugEnabled()) {
        StringBuilder builder = new StringBuilder("Handling request from ").append(HttpRequestUtil.getClientString(request)).append(" with parameters ").append(parameters).append(" and Accept");
        if (defaultAccept) {
            builder = builder.append(" default value");
        }
        builder = builder.append(": ").append(acceptValues.stream().map(Object::toString).collect(Collectors.joining(", ")));
        logger.debug(builder.toString());
    }
    try {
        ConfigurationProviderValue configurationProviderValue = configurationCache.get(new ConfigurationProviderKey(acceptValues, parameters));
        Configuration configuration = configurationProviderValue.getConfiguration();
        Response.ResponseBuilder ok = Response.ok();
        ok = ok.header("X-Content-Version", configuration.getVersion());
        ok = ok.type(configurationProviderValue.getMediaType());
        byte[] buffer = new byte[1024];
        int read;
        try (InputStream inputStream = configuration.getInputStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
            while ((read = inputStream.read(buffer)) >= 0) {
                outputStream.write(buffer, 0, read);
                md5.update(buffer, 0, read);
                sha256.update(buffer, 0, read);
            }
            ok = ok.header("Content-MD5", bytesToHex(md5.digest()));
            ok = ok.header("X-Content-SHA-256", bytesToHex(sha256.digest()));
            ok = ok.entity(outputStream.toByteArray());
        } catch (ConfigurationProviderException | IOException | NoSuchAlgorithmException e) {
            logger.error("Error reading or checksumming configuration file", e);
            throw new WebApplicationException(500);
        }
        return ok.build();
    } catch (AuthorizationException e) {
        logger.warn(HttpRequestUtil.getClientString(request) + " not authorized to access " + uriInfo, e);
        return Response.status(403).build();
    } catch (InvalidParameterException e) {
        logger.info(HttpRequestUtil.getClientString(request) + " made invalid request with " + HttpRequestUtil.getQueryString(request), e);
        return Response.status(400).entity("Invalid request.").build();
    } catch (ConfigurationProviderException e) {
        logger.warn("Unable to get configuration.", e);
        return Response.status(500).build();
    } catch (ExecutionException | UncheckedExecutionException e) {
        Throwable cause = e.getCause();
        if (cause instanceof WebApplicationException) {
            throw (WebApplicationException) cause;
        }
        logger.error(HttpRequestUtil.getClientString(request) + " made request with " + HttpRequestUtil.getQueryString(request) + " that caused error.", cause);
        return Response.status(500).entity("Internal error").build();
    }
}
Also used : Configuration(org.apache.nifi.minifi.c2.api.Configuration) WebApplicationException(javax.ws.rs.WebApplicationException) AuthorizationException(org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException) HashMap(java.util.HashMap) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) InvalidParameterException(org.apache.nifi.minifi.c2.api.InvalidParameterException) MediaType(javax.ws.rs.core.MediaType) ArrayList(java.util.ArrayList) List(java.util.List) MessageDigest(java.security.MessageDigest) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) ExecutionException(java.util.concurrent.ExecutionException) UncheckedExecutionException(com.google.common.util.concurrent.UncheckedExecutionException) InputStream(java.io.InputStream) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Response(javax.ws.rs.core.Response) HashMap(java.util.HashMap) Map(java.util.Map) GET(javax.ws.rs.GET)

Example 3 with AuthorizationException

use of org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException in project nifi-minifi by apache.

the class ConfigService method getContentTypes.

@GET
@Path("/contentTypes")
@Produces(MediaType.APPLICATION_JSON)
public Response getContentTypes(@Context HttpServletRequest request, @Context UriInfo uriInfo) {
    try {
        authorizer.authorize(SecurityContextHolder.getContext().getAuthentication(), uriInfo);
    } catch (AuthorizationException e) {
        logger.warn(HttpRequestUtil.getClientString(request) + " not authorized to access " + uriInfo, e);
        return Response.status(403).build();
    }
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    List<String> contentTypes;
    try {
        contentTypes = configurationProviderInfo.get().getContentTypes();
    } catch (ConfigurationProviderException e) {
        logger.warn("Unable to initialize content type information.", e);
        return Response.status(500).build();
    }
    try {
        objectMapper.writerWithDefaultPrettyPrinter().writeValue(byteArrayOutputStream, contentTypes);
    } catch (IOException e) {
        logger.warn("Unable to write configuration providers to output stream.", e);
        return Response.status(500).build();
    }
    return Response.ok().type(MediaType.APPLICATION_JSON_TYPE).entity(byteArrayOutputStream.toByteArray()).build();
}
Also used : ConfigurationProviderException(org.apache.nifi.minifi.c2.api.ConfigurationProviderException) AuthorizationException(org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException) ByteArrayOutputStream(java.io.ByteArrayOutputStream) IOException(java.io.IOException) Path(javax.ws.rs.Path) Produces(javax.ws.rs.Produces) GET(javax.ws.rs.GET)

Aggregations

IOException (java.io.IOException)3 ConfigurationProviderException (org.apache.nifi.minifi.c2.api.ConfigurationProviderException)3 AuthorizationException (org.apache.nifi.minifi.c2.api.security.authorization.AuthorizationException)3 ByteArrayOutputStream (java.io.ByteArrayOutputStream)2 InputStream (java.io.InputStream)2 List (java.util.List)2 Map (java.util.Map)2 GET (javax.ws.rs.GET)2 Configuration (org.apache.nifi.minifi.c2.api.Configuration)2 InvalidParameterException (org.apache.nifi.minifi.c2.api.InvalidParameterException)2 ObjectMapper (com.fasterxml.jackson.databind.ObjectMapper)1 UncheckedExecutionException (com.google.common.util.concurrent.UncheckedExecutionException)1 OutputStream (java.io.OutputStream)1 UnsupportedEncodingException (java.io.UnsupportedEncodingException)1 HttpURLConnection (java.net.HttpURLConnection)1 URLEncoder (java.net.URLEncoder)1 StandardCharsets (java.nio.charset.StandardCharsets)1 GeneralSecurityException (java.security.GeneralSecurityException)1 MessageDigest (java.security.MessageDigest)1 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)1