Search in sources :

Example 6 with CamelProperties

use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.

the class EndpointResourceTest method testEndpointTypeQuery.

@ParameterizedTest
@MethodSource
void testEndpointTypeQuery(Set<EndpointType> types) {
    String tenant = "limiter";
    String orgId = "limiter2";
    String userName = "user";
    String identityHeaderValue = TestHelpers.encodeRHIdentityInfo(tenant, orgId, userName);
    Header identityHeader = TestHelpers.createRHIdentityHeader(identityHeaderValue);
    MockServerConfig.addMockRbacAccess(identityHeaderValue, MockServerConfig.RbacAccess.FULL_ACCESS);
    // Add webhook
    WebhookProperties properties = new WebhookProperties();
    properties.setMethod(HttpType.POST);
    properties.setDisableSslVerification(false);
    properties.setSecretToken("my-super-secret-token");
    properties.setUrl(getMockServerUrl());
    Endpoint ep = new Endpoint();
    ep.setType(EndpointType.WEBHOOK);
    ep.setName("endpoint to find");
    ep.setDescription("needle in the haystack");
    ep.setEnabled(true);
    ep.setProperties(properties);
    Response response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(ep)).post("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
    JsonObject responsePoint = new JsonObject(response.getBody().asString());
    responsePoint.mapTo(Endpoint.class);
    assertNotNull(responsePoint.getString("id"));
    // Add Camel
    CamelProperties camelProperties = new CamelProperties();
    camelProperties.setDisableSslVerification(false);
    camelProperties.setSecretToken("my-super-secret-token");
    camelProperties.setUrl(getMockServerUrl());
    camelProperties.setExtras(new HashMap<>());
    Endpoint camelEp = new Endpoint();
    camelEp.setType(EndpointType.CAMEL);
    camelEp.setSubType("demo");
    camelEp.setName("endpoint to find");
    camelEp.setDescription("needle in the haystack");
    camelEp.setEnabled(true);
    camelEp.setProperties(camelProperties);
    response = given().header(identityHeader).when().contentType(JSON).body(Json.encode(camelEp)).post("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
    responsePoint = new JsonObject(response.getBody().asString());
    responsePoint.mapTo(Endpoint.class);
    assertNotNull(responsePoint.getString("id"));
    // Fetch the list to ensure everything was inserted correctly.
    response = given().header(identityHeader).when().get("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
    EndpointPage endpointPage = Json.decodeValue(response.getBody().asString(), EndpointPage.class);
    List<Endpoint> endpoints = endpointPage.getData();
    assertEquals(2, endpoints.size());
    // Fetch the list with types
    response = given().header(identityHeader).queryParam("type", types).when().get("/endpoints").then().statusCode(200).contentType(JSON).extract().response();
    endpointPage = Json.decodeValue(response.getBody().asString(), EndpointPage.class);
    endpoints = endpointPage.getData();
    // Ensure there is only the requested types
    assertEquals(types, endpoints.stream().map(Endpoint::getType).collect(Collectors.toSet()));
}
Also used : Response(io.restassured.response.Response) EndpointPage(com.redhat.cloud.notifications.routers.models.EndpointPage) Header(io.restassured.http.Header) Endpoint(com.redhat.cloud.notifications.models.Endpoint) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) JsonObject(io.vertx.core.json.JsonObject) ParameterizedTest(org.junit.jupiter.params.ParameterizedTest) MethodSource(org.junit.jupiter.params.provider.MethodSource)

Example 7 with CamelProperties

use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.

the class EndpointResource method createEndpoint.

@POST
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed(ConsoleIdentityProvider.RBAC_WRITE_INTEGRATIONS_ENDPOINTS)
@Transactional
public Endpoint createEndpoint(@Context SecurityContext sec, @NotNull @Valid Endpoint endpoint) {
    checkSystemEndpoint(endpoint.getType());
    RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
    endpoint.setAccountId(principal.getAccount());
    if (endpoint.getProperties() == null) {
        throw new BadRequestException("Properties is required");
    }
    if (obEnabled) {
        // TODO NOTIF-429 - see similar in EndpointResources#createEndpoint
        String endpointSubType;
        if (endpoint.getSubType() != null) {
            endpointSubType = endpoint.getSubType();
        } else {
            if (endpoint.getType() == EndpointType.CAMEL) {
                endpointSubType = endpoint.getProperties(CamelProperties.class).getSubType();
            } else {
                // No Camel endpoint, so we can skip
                endpointSubType = "not-defined";
            }
        }
        if (endpointSubType != null && endpointSubType.equals("slack")) {
            CamelProperties properties = endpoint.getProperties(CamelProperties.class);
            String processorName = "p-" + endpoint.getAccountId() + "-" + UUID.randomUUID();
            properties.getExtras().put(OB_PROCESSOR_NAME, processorName);
            String processorId = null;
            try {
                processorId = setupOpenBridgeProcessor(endpoint, properties, processorName);
            } catch (Exception e) {
                LOGGER.warn("Processor setup failed: " + e.getMessage());
                throw new InternalServerErrorException("Can't set up the endpoint");
            }
            // TODO find a better place for these, that should not be
            // visible to users / OB actions
            // See also CamelTypeProcessor#callOpenBridge
            properties.getExtras().put(OB_PROCESSOR_ID, processorId);
        }
    }
    return endpointRepository.createEndpoint(endpoint);
}
Also used : RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) NotFoundException(javax.ws.rs.NotFoundException) RolesAllowed(javax.annotation.security.RolesAllowed) POST(javax.ws.rs.POST) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Transactional(javax.transaction.Transactional)

Example 8 with CamelProperties

use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.

the class EndpointResource method deleteEndpoint.

@DELETE
@Path("/{id}")
@RolesAllowed(ConsoleIdentityProvider.RBAC_WRITE_INTEGRATIONS_ENDPOINTS)
@APIResponse(responseCode = "204", description = "The integration has been deleted", content = @Content(schema = @Schema(type = SchemaType.STRING)))
@Transactional
public Response deleteEndpoint(@Context SecurityContext sec, @PathParam("id") UUID id) {
    RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
    EndpointType endpointType = endpointRepository.getEndpointTypeById(principal.getAccount(), id);
    checkSystemEndpoint(endpointType);
    if (obEnabled) {
        Endpoint e = endpointRepository.getEndpoint(principal.getAccount(), id);
        if (e != null) {
            EndpointProperties properties = e.getProperties();
            if (properties instanceof CamelProperties) {
                CamelProperties cp = (CamelProperties) properties;
                // Special case wrt OpenBridge
                if (e.getSubType().equals("slack")) {
                    String processorId = cp.getExtras().get(OB_PROCESSOR_ID);
                    if (processorId != null) {
                        // Should not be null under normal operations.
                        try {
                            bridgeApiService.deleteProcessor(bridge.getId(), processorId, bridgeAuth.getToken());
                        } catch (Exception ex) {
                            LOGGER.warn("Removal of OB processor failed:" + ex.getMessage());
                        // Nothing more we can do
                        }
                    } else {
                        LOGGER.warn("ProcessorId was null for endpoint " + id.toString());
                    }
                }
            }
        }
    }
    endpointRepository.deleteEndpoint(principal.getAccount(), id);
    return Response.noContent().build();
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) EndpointType(com.redhat.cloud.notifications.models.EndpointType) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) EndpointProperties(com.redhat.cloud.notifications.models.EndpointProperties) BadRequestException(javax.ws.rs.BadRequestException) InternalServerErrorException(javax.ws.rs.InternalServerErrorException) NotFoundException(javax.ws.rs.NotFoundException) Path(javax.ws.rs.Path) DELETE(javax.ws.rs.DELETE) RolesAllowed(javax.annotation.security.RolesAllowed) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Transactional(javax.transaction.Transactional)

Example 9 with CamelProperties

use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.

the class EndpointRepository method updateEndpoint.

@Transactional
public boolean updateEndpoint(Endpoint endpoint) {
    // TODO Update could fail because the item did not exist, throw 404 in that case?
    // TODO Fix transaction so that we don't end up with half the updates applied
    String endpointQuery = "UPDATE Endpoint SET name = :name, description = :description, enabled = :enabled " + "WHERE accountId = :accountId AND id = :id";
    String webhookQuery = "UPDATE WebhookProperties SET url = :url, method = :method, " + "disableSslVerification = :disableSslVerification, secretToken = :secretToken WHERE endpoint.id = :endpointId";
    String camelQuery = "UPDATE CamelProperties SET url = :url, extras = :extras, " + "basicAuthentication = :basicAuthentication, " + "disableSslVerification = :disableSslVerification, secretToken = :secretToken WHERE endpoint.id = :endpointId";
    if (endpoint.getType() == EndpointType.EMAIL_SUBSCRIPTION) {
        throw new RuntimeException("Unable to update an endpoint of type EMAIL_SUBSCRIPTION");
    }
    int endpointRowCount = entityManager.createQuery(endpointQuery).setParameter("name", endpoint.getName()).setParameter("description", endpoint.getDescription()).setParameter("enabled", endpoint.isEnabled()).setParameter("accountId", endpoint.getAccountId()).setParameter("id", endpoint.getId()).executeUpdate();
    if (endpointRowCount == 0) {
        return false;
    } else if (endpoint.getProperties() == null) {
        return true;
    } else {
        switch(endpoint.getType()) {
            case WEBHOOK:
                WebhookProperties properties = endpoint.getProperties(WebhookProperties.class);
                return entityManager.createQuery(webhookQuery).setParameter("url", properties.getUrl()).setParameter("method", properties.getMethod()).setParameter("disableSslVerification", properties.getDisableSslVerification()).setParameter("secretToken", properties.getSecretToken()).setParameter("endpointId", endpoint.getId()).executeUpdate() > 0;
            case CAMEL:
                CamelProperties cAttr = (CamelProperties) endpoint.getProperties();
                return entityManager.createQuery(camelQuery).setParameter("url", cAttr.getUrl()).setParameter("disableSslVerification", cAttr.getDisableSslVerification()).setParameter("secretToken", cAttr.getSecretToken()).setParameter("endpointId", endpoint.getId()).setParameter("extras", cAttr.getExtras()).setParameter("basicAuthentication", cAttr.getBasicAuthentication()).executeUpdate() > 0;
            default:
                return true;
        }
    }
}
Also used : WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Transactional(javax.transaction.Transactional)

Example 10 with CamelProperties

use of com.redhat.cloud.notifications.models.CamelProperties in project notifications-backend by RedHatInsights.

the class CamelTypeProcessorTest method testCamelEndpointProcessing.

@Test
void testCamelEndpointProcessing() {
    // We need input data for the test.
    Event event = buildEvent();
    Endpoint endpoint1 = buildCamelEndpoint(event.getAction().getAccountId());
    CamelProperties properties1 = endpoint1.getProperties(CamelProperties.class);
    Endpoint endpoint2 = buildCamelEndpoint(event.getAction().getAccountId());
    // Let's trigger the processing.
    List<NotificationHistory> result = processor.process(event, List.of(endpoint1, endpoint2));
    // Two endpoints should have been processed.
    assertEquals(2, result.size());
    // Metrics should report the same thing.
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 2, SUB_TYPE_KEY, SUB_TYPE);
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0, SUB_TYPE_KEY, "other-type");
    micrometerAssertionHelper.assertCounterIncrement(PROCESSED_COUNTER_NAME, 0);
    // Let's have a look at the first result entry fields.
    assertEquals(event, result.get(0).getEvent());
    assertEquals(endpoint1, result.get(0).getEndpoint());
    assertEquals(CAMEL, result.get(0).getEndpointType());
    assertNotNull(result.get(0).getInvocationTime());
    // The invocation will be complete when the response from Camel has been received.
    assertFalse(result.get(0).isInvocationResult());
    // Now let's check the Kafka messages sent to the outgoing channel.
    InMemorySink<String> inMemorySink = inMemoryConnector.sink(TOCAMEL_CHANNEL);
    // The channel should have received two messages.
    assertEquals(2, inMemorySink.received().size());
    // We'll only check the payload and metadata of the first Kafka message.
    Message<String> message = inMemorySink.received().get(0);
    // The payload should contain the action events.
    JsonObject payload = new JsonObject(message.getPayload());
    assertNotNull(payload.getJsonArray("events").getJsonObject(0).getString("payload"));
    // The processor added a 'notif-metadata' field to the payload, let's have a look at it.
    JsonObject notifMetadata = payload.getJsonObject(NOTIF_METADATA_KEY);
    assertEquals(properties1.getDisableSslVerification().toString(), notifMetadata.getString("trustAll"));
    assertEquals(properties1.getUrl(), notifMetadata.getString("url"));
    assertEquals(endpoint1.getSubType(), notifMetadata.getString("type"));
    // Todo: NOTIF-429 backward compatibility change - Remove soon.
    assertEquals(properties1.getSubType(), notifMetadata.getString("type"));
    assertEquals(new MapConverter().convertToDatabaseColumn(properties1.getExtras()), notifMetadata.getString("extras"));
    assertEquals(properties1.getSecretToken(), notifMetadata.getString(TOKEN_HEADER));
    checkBasicAuthentication(notifMetadata, properties1.getBasicAuthentication());
    // Finally, we need to check the Kafka message metadata.
    UUID historyId = result.get(0).getId();
    checkKafkaMetadata(message, historyId, endpoint1.getSubType());
    checkCloudEventMetadata(message, historyId, endpoint1.getAccountId(), endpoint1.getSubType());
    checkTracingMetadata(message);
}
Also used : Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MapConverter(com.redhat.cloud.notifications.db.converters.MapConverter) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) UUID(java.util.UUID) Test(org.junit.jupiter.api.Test) QuarkusTest(io.quarkus.test.junit.QuarkusTest)

Aggregations

CamelProperties (com.redhat.cloud.notifications.models.CamelProperties)11 Endpoint (com.redhat.cloud.notifications.models.Endpoint)10 JsonObject (io.vertx.core.json.JsonObject)5 HashMap (java.util.HashMap)5 BasicAuthentication (com.redhat.cloud.notifications.models.BasicAuthentication)4 QuarkusTest (io.quarkus.test.junit.QuarkusTest)4 Header (io.restassured.http.Header)4 Test (org.junit.jupiter.api.Test)4 ParameterizedTest (org.junit.jupiter.params.ParameterizedTest)4 DbIsolatedTest (com.redhat.cloud.notifications.db.DbIsolatedTest)3 Transactional (javax.transaction.Transactional)3 RhIdPrincipal (com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal)2 MapConverter (com.redhat.cloud.notifications.db.converters.MapConverter)2 NotificationHistory (com.redhat.cloud.notifications.models.NotificationHistory)2 WebhookProperties (com.redhat.cloud.notifications.models.WebhookProperties)2 UUID (java.util.UUID)2 RolesAllowed (javax.annotation.security.RolesAllowed)2 BadRequestException (javax.ws.rs.BadRequestException)2 InternalServerErrorException (javax.ws.rs.InternalServerErrorException)2 NotFoundException (javax.ws.rs.NotFoundException)2