Search in sources :

Example 1 with EmailSubscriptionProperties

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

the class InternalResource method updateDefaultBehaviorGroupActions.

@PUT
@Path("/behaviorGroups/default/{behaviorGroupId}/actions")
@Consumes(APPLICATION_JSON)
@Produces(TEXT_PLAIN)
@Operation(summary = "Update the list of actions of a default behavior group.")
@APIResponse(responseCode = "200", content = @Content(schema = @Schema(type = SchemaType.STRING)))
@Transactional
@RolesAllowed(ConsoleIdentityProvider.RBAC_INTERNAL_ADMIN)
public Response updateDefaultBehaviorGroupActions(@PathParam("behaviorGroupId") UUID behaviorGroupId, List<RequestDefaultBehaviorGroupPropertyList> propertiesList) {
    if (propertiesList == null) {
        throw new BadRequestException("The request body must contain a list of EmailSubscriptionProperties");
    }
    if (propertiesList.size() != propertiesList.stream().distinct().count()) {
        throw new BadRequestException("The list of EmailSubscriptionProperties should not contain duplicates");
    }
    List<Endpoint> endpoints = propertiesList.stream().map(p -> {
        EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
        properties.setOnlyAdmins(p.isOnlyAdmins());
        properties.setIgnorePreferences(p.isIgnorePreferences());
        return endpointRepository.getOrCreateEmailSubscriptionEndpoint(null, properties);
    }).collect(Collectors.toList());
    Response.Status status = behaviorGroupRepository.updateDefaultBehaviorGroupActions(behaviorGroupId, endpoints.stream().distinct().map(Endpoint::getId).collect(Collectors.toList()));
    return Response.status(status).build();
}
Also used : RedirectionException(javax.ws.rs.RedirectionException) CurrentStatus(com.redhat.cloud.notifications.models.CurrentStatus) RolesAllowed(javax.annotation.security.RolesAllowed) Produces(javax.ws.rs.Produces) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Path(javax.ws.rs.Path) SecurityContext(javax.ws.rs.core.SecurityContext) Valid(javax.validation.Valid) MediaType(javax.ws.rs.core.MediaType) Matcher(java.util.regex.Matcher) Consumes(javax.ws.rs.Consumes) SchemaType(org.eclipse.microprofile.openapi.annotations.enums.SchemaType) BadRequestException(javax.ws.rs.BadRequestException) InternalRoleAccess(com.redhat.cloud.notifications.models.InternalRoleAccess) URI(java.net.URI) StartupUtils(com.redhat.cloud.notifications.StartupUtils) BehaviorGroupRepository(com.redhat.cloud.notifications.db.repositories.BehaviorGroupRepository) APPLICATION_JSON(javax.ws.rs.core.MediaType.APPLICATION_JSON) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) DELETE(javax.ws.rs.DELETE) BAD_REQUEST(javax.ws.rs.core.Response.Status.BAD_REQUEST) Application(com.redhat.cloud.notifications.models.Application) Context(javax.ws.rs.core.Context) PermitAll(javax.annotation.security.PermitAll) Transactional(javax.transaction.Transactional) Operation(org.eclipse.microprofile.openapi.annotations.Operation) UUID(java.util.UUID) NotNull(javax.validation.constraints.NotNull) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) List(java.util.List) Response(javax.ws.rs.core.Response) Pattern(java.util.regex.Pattern) TEXT_PLAIN(javax.ws.rs.core.MediaType.TEXT_PLAIN) PathParam(javax.ws.rs.PathParam) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) GET(javax.ws.rs.GET) Logger(org.jboss.logging.Logger) EndpointRepository(com.redhat.cloud.notifications.db.repositories.EndpointRepository) API_INTERNAL(com.redhat.cloud.notifications.Constants.API_INTERNAL) Inject(javax.inject.Inject) EventType(com.redhat.cloud.notifications.models.EventType) OApiFilter(com.redhat.cloud.notifications.oapi.OApiFilter) ServerInfo(com.redhat.cloud.notifications.routers.internal.models.ServerInfo) BehaviorGroup(com.redhat.cloud.notifications.models.BehaviorGroup) RequestDefaultBehaviorGroupPropertyList(com.redhat.cloud.notifications.routers.internal.models.RequestDefaultBehaviorGroupPropertyList) ConsoleIdentityProvider(com.redhat.cloud.notifications.auth.ConsoleIdentityProvider) Content(org.eclipse.microprofile.openapi.annotations.media.Content) BundleRepository(com.redhat.cloud.notifications.db.repositories.BundleRepository) ApplicationRepository(com.redhat.cloud.notifications.db.repositories.ApplicationRepository) POST(javax.ws.rs.POST) Schema(org.eclipse.microprofile.openapi.annotations.media.Schema) AddApplicationRequest(com.redhat.cloud.notifications.routers.internal.models.AddApplicationRequest) Bundle(com.redhat.cloud.notifications.models.Bundle) InternalRoleAccessRepository(com.redhat.cloud.notifications.db.repositories.InternalRoleAccessRepository) SecurityContextUtil(com.redhat.cloud.notifications.routers.SecurityContextUtil) StatusRepository(com.redhat.cloud.notifications.db.repositories.StatusRepository) PUT(javax.ws.rs.PUT) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) Response(javax.ws.rs.core.Response) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) APIResponse(org.eclipse.microprofile.openapi.annotations.responses.APIResponse) RolesAllowed(javax.annotation.security.RolesAllowed) Consumes(javax.ws.rs.Consumes) Produces(javax.ws.rs.Produces) Operation(org.eclipse.microprofile.openapi.annotations.Operation) PUT(javax.ws.rs.PUT) Transactional(javax.transaction.Transactional)

Example 2 with EmailSubscriptionProperties

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

the class EndpointResource method getOrCreateEmailSubscriptionEndpoint.

@POST
@Path("/system/email_subscription")
@Consumes(APPLICATION_JSON)
@Produces(APPLICATION_JSON)
@RolesAllowed(ConsoleIdentityProvider.RBAC_READ_INTEGRATIONS_ENDPOINTS)
@Transactional
public Endpoint getOrCreateEmailSubscriptionEndpoint(@Context SecurityContext sec, @NotNull @Valid RequestEmailSubscriptionProperties requestProps) {
    RhIdPrincipal principal = (RhIdPrincipal) sec.getUserPrincipal();
    if (requestProps.getGroupId() != null && requestProps.isOnlyAdmins()) {
        throw new BadRequestException(String.format("Cannot use RBAC groups and only admins in the same endpoint"));
    }
    if (requestProps.getGroupId() != null) {
        boolean isValid = rbacGroupValidator.validate(requestProps.getGroupId(), principal.getIdentity().rawIdentity);
        if (!isValid) {
            throw new BadRequestException(String.format("Invalid RBAC group identified with id %s", requestProps.getGroupId()));
        }
    }
    // Prevent from creating not public facing properties
    EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
    properties.setOnlyAdmins(requestProps.isOnlyAdmins());
    properties.setGroupId(requestProps.getGroupId());
    return endpointRepository.getOrCreateEmailSubscriptionEndpoint(principal.getAccount(), properties);
}
Also used : RequestEmailSubscriptionProperties(com.redhat.cloud.notifications.routers.models.RequestEmailSubscriptionProperties) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) RhIdPrincipal(com.redhat.cloud.notifications.auth.principal.rhid.RhIdPrincipal) BadRequestException(javax.ws.rs.BadRequestException) Path(javax.ws.rs.Path) 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 3 with EmailSubscriptionProperties

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

the class EndpointRepository method getOrCreateEmailSubscriptionEndpoint.

@Transactional
public Endpoint getOrCreateEmailSubscriptionEndpoint(String accountId, EmailSubscriptionProperties properties) {
    List<Endpoint> emailEndpoints = getEndpointsPerCompositeType(accountId, null, Set.of(new CompositeEndpointType(EndpointType.EMAIL_SUBSCRIPTION)), null, null);
    loadProperties(emailEndpoints);
    Optional<Endpoint> endpointOptional = emailEndpoints.stream().filter(endpoint -> properties.hasSameProperties(endpoint.getProperties(EmailSubscriptionProperties.class))).findFirst();
    if (endpointOptional.isPresent()) {
        return endpointOptional.get();
    }
    Endpoint endpoint = new Endpoint();
    endpoint.setProperties(properties);
    endpoint.setAccountId(accountId);
    endpoint.setEnabled(true);
    endpoint.setDescription("System email endpoint");
    endpoint.setName("Email endpoint");
    endpoint.setType(EndpointType.EMAIL_SUBSCRIPTION);
    return createEndpoint(endpoint);
}
Also used : CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Logger(org.jboss.logging.Logger) NoResultException(javax.persistence.NoResultException) Function(java.util.function.Function) Supplier(java.util.function.Supplier) Inject(javax.inject.Inject) HashSet(java.util.HashSet) WhereBuilder(com.redhat.cloud.notifications.db.builder.WhereBuilder) Map(java.util.Map) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) BadRequestException(javax.ws.rs.BadRequestException) Nullable(javax.annotation.Nullable) QueryBuilder(com.redhat.cloud.notifications.db.builder.QueryBuilder) CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) EndpointProperties(com.redhat.cloud.notifications.models.EndpointProperties) Transactional(javax.transaction.Transactional) Query(com.redhat.cloud.notifications.db.Query) Set(java.util.Set) EntityManager(javax.persistence.EntityManager) UUID(java.util.UUID) Collectors(java.util.stream.Collectors) NotFoundException(javax.ws.rs.NotFoundException) List(java.util.List) EndpointType(com.redhat.cloud.notifications.models.EndpointType) Optional(java.util.Optional) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Collections(java.util.Collections) CompositeEndpointType(com.redhat.cloud.notifications.models.CompositeEndpointType) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) Transactional(javax.transaction.Transactional)

Example 4 with EmailSubscriptionProperties

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

the class EndpointRepository method getOrCreateDefaultEmailSubscription.

/**
 * The purpose of this method is to find or create an EMAIL_SUBSCRIPTION endpoint with empty properties. This
 * endpoint is used to aggregate and store in the DB the email actions outcome, which will be used later by the
 * event log. The recipients of the current email action have already been resolved before this step, possibly from
 * multiple endpoints and recipients settings. The properties created below have no impact on the resolution of the
 * action recipients.
 */
public Endpoint getOrCreateDefaultEmailSubscription(String accountId) {
    String query = "FROM Endpoint WHERE accountId = :accountId AND compositeType.type = :endpointType";
    List<Endpoint> emailEndpoints = statelessSessionFactory.getCurrentSession().createQuery(query, Endpoint.class).setParameter("accountId", accountId).setParameter("endpointType", EMAIL_SUBSCRIPTION).getResultList();
    loadProperties(emailEndpoints);
    EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
    Optional<Endpoint> endpointOptional = emailEndpoints.stream().filter(endpoint -> properties.hasSameProperties(endpoint.getProperties(EmailSubscriptionProperties.class))).findFirst();
    if (endpointOptional.isPresent()) {
        return endpointOptional.get();
    }
    Endpoint endpoint = new Endpoint();
    endpoint.setProperties(properties);
    endpoint.setAccountId(accountId);
    endpoint.setEnabled(true);
    endpoint.setDescription("System email endpoint");
    endpoint.setName("Email endpoint");
    endpoint.setType(EMAIL_SUBSCRIPTION);
    endpoint.prePersist();
    properties.setEndpoint(endpoint);
    statelessSessionFactory.getCurrentSession().insert(endpoint);
    statelessSessionFactory.getCurrentSession().insert(endpoint.getProperties());
    return endpoint;
}
Also used : CamelProperties(com.redhat.cloud.notifications.models.CamelProperties) EndpointProperties(com.redhat.cloud.notifications.models.EndpointProperties) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) Endpoint(com.redhat.cloud.notifications.models.Endpoint) Logger(org.jboss.logging.Logger) Set(java.util.Set) EMAIL_SUBSCRIPTION(com.redhat.cloud.notifications.models.EndpointType.EMAIL_SUBSCRIPTION) UUID(java.util.UUID) CAMEL(com.redhat.cloud.notifications.models.EndpointType.CAMEL) Function(java.util.function.Function) Collectors(java.util.stream.Collectors) WEBHOOK(com.redhat.cloud.notifications.models.EndpointType.WEBHOOK) Inject(javax.inject.Inject) HashSet(java.util.HashSet) EventType(com.redhat.cloud.notifications.models.EventType) List(java.util.List) EndpointType(com.redhat.cloud.notifications.models.EndpointType) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) Map(java.util.Map) Optional(java.util.Optional) WebhookProperties(com.redhat.cloud.notifications.models.WebhookProperties) ApplicationScoped(javax.enterprise.context.ApplicationScoped) Endpoint(com.redhat.cloud.notifications.models.Endpoint) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties)

Example 5 with EmailSubscriptionProperties

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

the class EmailTest method testEmailSubscriptionInstantWrongPayload.

@Test
@Disabled
void testEmailSubscriptionInstantWrongPayload() {
    mockGetUsers(8);
    final String tenant = "instant-email-tenant-wrong-payload";
    final String[] usernames = { "username-1", "username-2", "username-4" };
    String bundle = "rhel";
    String application = "policies";
    for (String username : usernames) {
        subscribe(tenant, username, bundle, application);
    }
    final List<String> bodyRequests = new ArrayList<>();
    ExpectationResponseCallback verifyEmptyRequest = req -> {
        assertEquals(BOP_TOKEN, req.getHeader(EmailSender.BOP_APITOKEN_HEADER).get(0));
        assertEquals(BOP_CLIENT_ID, req.getHeader(EmailSender.BOP_CLIENT_ID_HEADER).get(0));
        assertEquals(BOP_ENV, req.getHeader(EmailSender.BOP_ENV_HEADER).get(0));
        bodyRequests.add(req.getBodyAsString());
        return response().withStatusCode(200);
    };
    HttpRequest postReq = getMockHttpRequest(verifyEmptyRequest);
    Action emailActionMessage = new Action();
    emailActionMessage.setBundle(bundle);
    emailActionMessage.setApplication(application);
    emailActionMessage.setTimestamp(LocalDateTime.of(2020, 10, 3, 15, 22, 13, 25));
    emailActionMessage.setEventType(TestHelpers.eventType);
    emailActionMessage.setRecipients(List.of());
    emailActionMessage.setContext(new Context.ContextBuilder().withAdditionalProperty("inventory_id-wrong", "host-01").withAdditionalProperty("system_check_in-wrong", "2020-08-03T15:22:42.199046").withAdditionalProperty("display_name-wrong", "My test machine").withAdditionalProperty("tags-what?", List.of()).build());
    emailActionMessage.setEvents(List.of(new com.redhat.cloud.notifications.ingress.Event.EventBuilder().withMetadata(new Metadata.MetadataBuilder().build()).withPayload(new Payload.PayloadBuilder().withAdditionalProperty("foo", "bar").build()).build()));
    emailActionMessage.setAccountId(tenant);
    Event event = new Event();
    event.setAction(emailActionMessage);
    EmailSubscriptionProperties properties = new EmailSubscriptionProperties();
    Endpoint ep = new Endpoint();
    ep.setType(EndpointType.EMAIL_SUBSCRIPTION);
    ep.setName("positive feeling");
    ep.setDescription("needle in the haystack");
    ep.setEnabled(true);
    ep.setProperties(properties);
    try {
        List<NotificationHistory> historyEntries = statelessSessionFactory.withSession(statelessSession -> {
            return emailProcessor.process(event, List.of(ep));
        });
        // The processor returns a null history value but Multi does not support null values so the resulting Multi is empty.
        assertTrue(historyEntries.isEmpty());
        // No email, invalid payload
        assertEquals(0, bodyRequests.size());
    } catch (Exception e) {
        e.printStackTrace();
        fail(e);
    } finally {
        // Remove expectations
        MockServerLifecycleManager.getClient().clear(postReq);
    }
    clearSubscriptions();
}
Also used : INSTANT(com.redhat.cloud.notifications.models.EmailSubscriptionType.INSTANT) Assertions.fail(org.junit.jupiter.api.Assertions.fail) Assertions.assertNotNull(org.junit.jupiter.api.Assertions.assertNotNull) Arrays(java.util.Arrays) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) HttpRequest(org.mockserver.model.HttpRequest) Endpoint(com.redhat.cloud.notifications.models.Endpoint) ITUserResponse(com.redhat.cloud.notifications.recipients.itservice.pojo.response.ITUserResponse) LocalDateTime(java.time.LocalDateTime) Disabled(org.junit.jupiter.api.Disabled) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) MockServerLifecycleManager(com.redhat.cloud.notifications.MockServerLifecycleManager) ArrayList(java.util.ArrayList) Inject(javax.inject.Inject) InjectSpy(io.quarkus.test.junit.mockito.InjectSpy) ITUserRequest(com.redhat.cloud.notifications.recipients.itservice.pojo.request.ITUserRequest) Event(com.redhat.cloud.notifications.models.Event) JsonObject(io.vertx.core.json.JsonObject) Assertions.assertEquals(org.junit.jupiter.api.Assertions.assertEquals) Payload(com.redhat.cloud.notifications.ingress.Payload) Context(com.redhat.cloud.notifications.ingress.Context) InjectMock(io.quarkus.test.junit.mockito.InjectMock) RestClient(org.eclipse.microprofile.rest.client.inject.RestClient) Transactional(javax.transaction.Transactional) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) EntityManager(javax.persistence.EntityManager) Collectors(java.util.stream.Collectors) ITUserService(com.redhat.cloud.notifications.recipients.itservice.ITUserService) Test(org.junit.jupiter.api.Test) JsonArray(io.vertx.core.json.JsonArray) Mockito(org.mockito.Mockito) List(java.util.List) Authentication(com.redhat.cloud.notifications.recipients.itservice.pojo.response.Authentication) EndpointType(com.redhat.cloud.notifications.models.EndpointType) StatelessSessionFactory(com.redhat.cloud.notifications.db.StatelessSessionFactory) Assertions.assertTrue(org.junit.jupiter.api.Assertions.assertTrue) AccountRelationship(com.redhat.cloud.notifications.recipients.itservice.pojo.response.AccountRelationship) TestHelpers(com.redhat.cloud.notifications.TestHelpers) Metadata(com.redhat.cloud.notifications.ingress.Metadata) Action(com.redhat.cloud.notifications.ingress.Action) Comparator(java.util.Comparator) HttpResponse.response(org.mockserver.model.HttpResponse.response) PersonalInformation(com.redhat.cloud.notifications.recipients.itservice.pojo.response.PersonalInformation) HttpRequest(org.mockserver.model.HttpRequest) Action(com.redhat.cloud.notifications.ingress.Action) ExpectationResponseCallback(org.mockserver.mock.action.ExpectationResponseCallback) EmailSubscriptionProperties(com.redhat.cloud.notifications.models.EmailSubscriptionProperties) ArrayList(java.util.ArrayList) Endpoint(com.redhat.cloud.notifications.models.Endpoint) NotificationHistory(com.redhat.cloud.notifications.models.NotificationHistory) Event(com.redhat.cloud.notifications.models.Event) Test(org.junit.jupiter.api.Test) Disabled(org.junit.jupiter.api.Disabled)

Aggregations

EmailSubscriptionProperties (com.redhat.cloud.notifications.models.EmailSubscriptionProperties)8 Endpoint (com.redhat.cloud.notifications.models.Endpoint)7 List (java.util.List)5 Collectors (java.util.stream.Collectors)5 Inject (javax.inject.Inject)5 Transactional (javax.transaction.Transactional)5 EndpointType (com.redhat.cloud.notifications.models.EndpointType)4 StatelessSessionFactory (com.redhat.cloud.notifications.db.StatelessSessionFactory)3 WebhookProperties (com.redhat.cloud.notifications.models.WebhookProperties)3 JsonObject (io.vertx.core.json.JsonObject)3 HashSet (java.util.HashSet)3 UUID (java.util.UUID)3 EntityManager (javax.persistence.EntityManager)3 BadRequestException (javax.ws.rs.BadRequestException)3 Logger (org.jboss.logging.Logger)3 Test (org.junit.jupiter.api.Test)3 MockServerLifecycleManager (com.redhat.cloud.notifications.MockServerLifecycleManager)2 TestHelpers (com.redhat.cloud.notifications.TestHelpers)2 Action (com.redhat.cloud.notifications.ingress.Action)2 Context (com.redhat.cloud.notifications.ingress.Context)2