Search in sources :

Example 91 with BadRequestException

use of javax.ws.rs.BadRequestException in project cxf by apache.

the class JAXRSXmlSecTest method testPostEncryptedSignedBookInvalid.

@Test
public void testPostEncryptedSignedBookInvalid() throws Exception {
    String address = "https://localhost:" + test.port + "/xmlsec-validate/bookstore/books";
    Map<String, Object> properties = new HashMap<>();
    properties.put(SecurityConstants.CALLBACK_HANDLER, "org.apache.cxf.systest.jaxrs.security.saml.KeystorePasswordCallback");
    properties.put(SecurityConstants.ENCRYPT_USERNAME, "bob");
    properties.put(SecurityConstants.ENCRYPT_PROPERTIES, "org/apache/cxf/systest/jaxrs/security/bob.properties");
    properties.put(SecurityConstants.SIGNATURE_USERNAME, "alice");
    properties.put(SecurityConstants.SIGNATURE_PROPERTIES, "org/apache/cxf/systest/jaxrs/security/alice.properties");
    EncryptionProperties encryptionProperties = new EncryptionProperties();
    encryptionProperties.setEncryptionSymmetricKeyAlgo("http://www.w3.org/2009/xmlenc11#aes128-gcm");
    encryptionProperties.setEncryptionKeyIdType(RSSecurityUtils.X509_CERT);
    try {
        doTestPostEncryptedBook(address, true, properties, encryptionProperties, true, test.streaming);
    } catch (BadRequestException ex) {
        assertEquals(400, ex.getResponse().getStatus());
    }
}
Also used : HashMap(java.util.HashMap) BadRequestException(javax.ws.rs.BadRequestException) EncryptionProperties(org.apache.cxf.rs.security.xml.EncryptionProperties) Test(org.junit.Test)

Example 92 with BadRequestException

use of javax.ws.rs.BadRequestException in project cxf by apache.

the class JAXRSXmlSecTest method testUnsignedServerResponse.

@Test
public void testUnsignedServerResponse() throws Exception {
    if (STAX_PORT.equals(test.port)) {
        // We are only testing the client here
        return;
    }
    String address = "https://localhost:" + test.port + "/xmlnosigresponse/bookstore/books";
    JAXRSClientFactoryBean bean = new JAXRSClientFactoryBean();
    bean.setAddress(address);
    SpringBusFactory bf = new SpringBusFactory();
    URL busFile = JAXRSXmlSecTest.class.getResource("client.xml");
    Bus springBus = bf.createBus(busFile.toString());
    bean.setBus(springBus);
    Map<String, Object> properties = new HashMap<>();
    properties.put(SecurityConstants.CALLBACK_HANDLER, "org.apache.cxf.systest.jaxrs.security.saml.KeystorePasswordCallback");
    properties.put(SecurityConstants.SIGNATURE_USERNAME, "alice");
    properties.put(SecurityConstants.SIGNATURE_PROPERTIES, "org/apache/cxf/systest/jaxrs/security/alice.properties");
    bean.setProperties(properties);
    if (test.streaming) {
        XmlSecOutInterceptor sigOutInterceptor = new XmlSecOutInterceptor();
        sigOutInterceptor.setSignRequest(true);
        bean.getOutInterceptors().add(sigOutInterceptor);
        XmlSecInInterceptor sigInInterceptor = new XmlSecInInterceptor();
        sigInInterceptor.setRequireSignature(true);
        bean.setProvider(sigInInterceptor);
    } else {
        XmlSigOutInterceptor sigOutInterceptor = new XmlSigOutInterceptor();
        bean.getOutInterceptors().add(sigOutInterceptor);
        XmlSigInInterceptor sigInInterceptor = new XmlSigInInterceptor();
        bean.getInInterceptors().add(sigInInterceptor);
    }
    WebClient wc = bean.createWebClient();
    WebClient.getConfig(wc).getHttpConduit().getClient().setReceiveTimeout(10000000L);
    try {
        wc.type("application/xml").post(new Book("CXF", 126L), Book.class);
        fail("Failure expected on an unsigned response message");
    } catch (ProcessingException ex) {
        assertTrue(ex.getCause() instanceof BadRequestException);
    }
}
Also used : Bus(org.apache.cxf.Bus) XmlSigOutInterceptor(org.apache.cxf.rs.security.xml.XmlSigOutInterceptor) JAXRSClientFactoryBean(org.apache.cxf.jaxrs.client.JAXRSClientFactoryBean) HashMap(java.util.HashMap) XmlSecInInterceptor(org.apache.cxf.rs.security.xml.XmlSecInInterceptor) XmlSecOutInterceptor(org.apache.cxf.rs.security.xml.XmlSecOutInterceptor) WebClient(org.apache.cxf.jaxrs.client.WebClient) URL(java.net.URL) XmlSigInInterceptor(org.apache.cxf.rs.security.xml.XmlSigInInterceptor) SpringBusFactory(org.apache.cxf.bus.spring.SpringBusFactory) Book(org.apache.cxf.systest.jaxrs.security.Book) BadRequestException(javax.ws.rs.BadRequestException) ProcessingException(javax.ws.rs.ProcessingException) Test(org.junit.Test)

Example 93 with BadRequestException

use of javax.ws.rs.BadRequestException in project cxf by apache.

the class AbstractSignatureInFilter method verifyDigest.

protected byte[] verifyDigest(MultivaluedMap<String, String> headers, InputStream entityStream) {
    byte[] messageBody = null;
    if (!enabled) {
        return messageBody;
    }
    // configuration to require that the digest is signed (and hence present)
    if (entityStream != null && headers.containsKey("Digest")) {
        LOG.fine("Digesting message body");
        try {
            messageBody = IOUtils.readBytesFromStream(entityStream);
        } catch (IOException e) {
            throw new DigestFailureException("failed to validate the digest", e);
        }
        DigestVerifier digestVerifier = new DigestVerifier();
        try {
            digestVerifier.inspectDigest(messageBody, headers);
        } catch (DigestFailureException | DifferentDigestsException | MissingDigestException ex) {
            Message message = PhaseInterceptorChain.getCurrentMessage();
            if (MessageUtils.isRequestor(message)) {
                throw ex;
            }
            throw new BadRequestException(ex);
        }
    }
    LOG.fine("Finished digest message verification process");
    return messageBody;
}
Also used : Message(org.apache.cxf.message.Message) DigestFailureException(org.apache.cxf.rs.security.httpsignature.exception.DigestFailureException) BadRequestException(javax.ws.rs.BadRequestException) IOException(java.io.IOException) MissingDigestException(org.apache.cxf.rs.security.httpsignature.exception.MissingDigestException) DifferentDigestsException(org.apache.cxf.rs.security.httpsignature.exception.DifferentDigestsException) DigestVerifier(org.apache.cxf.rs.security.httpsignature.DigestVerifier)

Example 94 with BadRequestException

use of javax.ws.rs.BadRequestException in project openremote by openremote.

the class AssetDatapointResourceImpl method getDatapointExport.

@Override
public void getDatapointExport(AsyncResponse asyncResponse, String attributeRefsString, long fromTimestamp, long toTimestamp) {
    try {
        AttributeRef[] attributeRefs = JSON.readValue(attributeRefsString, AttributeRef[].class);
        for (AttributeRef attributeRef : attributeRefs) {
            if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), attributeRef.getId())) {
                throw new WebApplicationException(Response.Status.FORBIDDEN);
            }
            Asset<?> asset = assetStorageService.find(attributeRef.getId(), true);
            if (asset == null) {
                throw new WebApplicationException(Response.Status.NOT_FOUND);
            }
            if (!isTenantActiveAndAccessible(asset.getRealm())) {
                DATA_EXPORT_LOG.info("Forbidden access for user '" + getUsername() + "': " + asset);
                throw new WebApplicationException(Response.Status.FORBIDDEN);
            }
            asset.getAttribute(attributeRef.getName()).orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
        }
        DATA_EXPORT_LOG.info("User '" + getUsername() + "' started data export for " + attributeRefsString + " from " + fromTimestamp + " to " + toTimestamp);
        ScheduledFuture<File> exportFuture = assetDatapointService.exportDatapoints(attributeRefs, fromTimestamp, toTimestamp);
        asyncResponse.register((ConnectionCallback) disconnected -> {
            exportFuture.cancel(true);
        });
        File exportFile = null;
        try {
            exportFile = exportFuture.get();
            ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
            FileInputStream fin = new FileInputStream(exportFile);
            ZipEntry zipEntry = new ZipEntry(exportFile.getName());
            zipOut.putNextEntry(zipEntry);
            IOUtils.copy(fin, zipOut);
            zipOut.closeEntry();
            zipOut.close();
            fin.close();
            response.setContentType("application/zip");
            response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"dataexport.zip\"");
            asyncResponse.resume(response);
        } catch (Exception ex) {
            exportFuture.cancel(true);
            asyncResponse.resume(new WebApplicationException(Response.Status.INTERNAL_SERVER_ERROR));
            DATA_EXPORT_LOG.log(Level.SEVERE, "Exception in ScheduledFuture: ", ex);
        } finally {
            if (exportFile != null && exportFile.exists()) {
                try {
                    exportFile.delete();
                } catch (Exception e) {
                    DATA_EXPORT_LOG.log(Level.SEVERE, "Failed to delete temporary export file: " + exportFile.getPath(), e);
                }
            }
        }
    } catch (JsonProcessingException ex) {
        asyncResponse.resume(new BadRequestException(ex));
    }
}
Also used : AssetStorageService(org.openremote.manager.asset.AssetStorageService) ZipOutputStream(java.util.zip.ZipOutputStream) DatapointInterval(org.openremote.model.datapoint.DatapointInterval) ScheduledFuture(java.util.concurrent.ScheduledFuture) AttributeRef(org.openremote.model.attribute.AttributeRef) AssetDatapointResource(org.openremote.model.datapoint.AssetDatapointResource) LocalDateTime(java.time.LocalDateTime) DATA(org.openremote.model.syslog.SyslogCategory.DATA) JSON(org.openremote.model.util.ValueUtil.JSON) ManagerWebResource(org.openremote.manager.web.ManagerWebResource) Level(java.util.logging.Level) Attribute(org.openremote.model.attribute.Attribute) BadRequestException(javax.ws.rs.BadRequestException) SyslogCategory(org.openremote.model.syslog.SyslogCategory) ZipEntry(java.util.zip.ZipEntry) NotSupportedException(javax.ws.rs.NotSupportedException) ManagerIdentityService(org.openremote.manager.security.ManagerIdentityService) Asset(org.openremote.model.asset.Asset) AsyncResponse(javax.ws.rs.container.AsyncResponse) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) Instant(java.time.Instant) Logger(java.util.logging.Logger) BeanParam(javax.ws.rs.BeanParam) ZoneId(java.time.ZoneId) ValueDatapoint(org.openremote.model.datapoint.ValueDatapoint) IOUtils(org.apache.commons.io.IOUtils) HttpHeaders(javax.ws.rs.core.HttpHeaders) Response(javax.ws.rs.core.Response) java.io(java.io) TimerService(org.openremote.container.timer.TimerService) DatapointPeriod(org.openremote.model.datapoint.DatapointPeriod) WebApplicationException(javax.ws.rs.WebApplicationException) ConnectionCallback(javax.ws.rs.container.ConnectionCallback) RequestParams(org.openremote.model.http.RequestParams) AttributeRef(org.openremote.model.attribute.AttributeRef) WebApplicationException(javax.ws.rs.WebApplicationException) ZipEntry(java.util.zip.ZipEntry) BadRequestException(javax.ws.rs.BadRequestException) NotSupportedException(javax.ws.rs.NotSupportedException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException) WebApplicationException(javax.ws.rs.WebApplicationException) ZipOutputStream(java.util.zip.ZipOutputStream) BadRequestException(javax.ws.rs.BadRequestException) JsonProcessingException(com.fasterxml.jackson.core.JsonProcessingException)

Example 95 with BadRequestException

use of javax.ws.rs.BadRequestException in project openremote by openremote.

the class AssetDatapointResourceImpl method getDatapoints.

@Override
public ValueDatapoint<?>[] getDatapoints(@BeanParam RequestParams requestParams, String assetId, String attributeName, DatapointInterval interval, Integer stepSize, long fromTimestamp, long toTimestamp) {
    try {
        if (isRestrictedUser() && !assetStorageService.isUserAsset(getUserId(), assetId)) {
            throw new WebApplicationException(Response.Status.FORBIDDEN);
        }
        Asset<?> asset = assetStorageService.find(assetId, true);
        if (asset == null) {
            throw new WebApplicationException(Response.Status.NOT_FOUND);
        }
        if (!isTenantActiveAndAccessible(asset.getRealm())) {
            LOG.info("Forbidden access for user '" + getUsername() + "': " + asset);
            throw new WebApplicationException(Response.Status.FORBIDDEN);
        }
        Attribute<?> attribute = asset.getAttribute(attributeName).orElseThrow(() -> new WebApplicationException(Response.Status.NOT_FOUND));
        return assetDatapointService.getValueDatapoints(assetId, attribute, interval, stepSize, LocalDateTime.ofInstant(Instant.ofEpochMilli(fromTimestamp), ZoneId.systemDefault()), LocalDateTime.ofInstant(Instant.ofEpochMilli(toTimestamp), ZoneId.systemDefault()));
    } catch (IllegalStateException ex) {
        throw new BadRequestException(ex);
    } catch (UnsupportedOperationException ex) {
        throw new NotSupportedException(ex);
    }
}
Also used : WebApplicationException(javax.ws.rs.WebApplicationException) BadRequestException(javax.ws.rs.BadRequestException) NotSupportedException(javax.ws.rs.NotSupportedException)

Aggregations

BadRequestException (javax.ws.rs.BadRequestException)238 Path (javax.ws.rs.Path)92 ApiOperation (io.swagger.annotations.ApiOperation)80 POST (javax.ws.rs.POST)65 Consumes (javax.ws.rs.Consumes)61 Produces (javax.ws.rs.Produces)55 AuditEvent (org.graylog2.audit.jersey.AuditEvent)52 NotFoundException (javax.ws.rs.NotFoundException)42 Timed (com.codahale.metrics.annotation.Timed)40 PUT (javax.ws.rs.PUT)40 ApiResponses (io.swagger.annotations.ApiResponses)38 Test (org.junit.Test)34 GET (javax.ws.rs.GET)32 IOException (java.io.IOException)30 Response (javax.ws.rs.core.Response)27 RequiresPermissions (org.apache.shiro.authz.annotation.RequiresPermissions)27 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)26 NoAuditEvent (org.graylog2.audit.jersey.NoAuditEvent)26 URI (java.net.URI)24 HashMap (java.util.HashMap)22