Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions extensions/router/router-service/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,21 @@
<artifactId>slf4j-api</artifactId>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>
</dependencies>

<build>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,15 @@ public void setConfigSharingService(ConfigSharingService configSharingService) {
}

public String extractProfilesBySegment(ExportConfiguration exportConfiguration) {
Object segmentProperty = exportConfiguration.getProperty("segment");
if (segmentProperty == null || StringUtils.isBlank(segmentProperty.toString())) {
throw new IllegalArgumentException("Export segment is required");
}
Map<String, String> mapping = (Map<String, String>) exportConfiguration.getProperty("mapping");
if (mapping == null || mapping.isEmpty()) {
throw new IllegalArgumentException("Export mapping is required");
}

Collection<PropertyType> propertiesDef = persistenceService.query("target", "profiles", null, PropertyType.class);

Condition segmentCondition = new Condition();
Expand Down Expand Up @@ -97,6 +106,9 @@ public String convertProfileToCSVLine(Profile profile, ExportConfiguration expor

public String convertProfileToCSVLine(Profile profile, ExportConfiguration exportConfiguration, Collection<PropertyType> propertiesDef) {
Map<String, String> mapping = (Map<String, String>) exportConfiguration.getProperty("mapping");
if (mapping == null || mapping.isEmpty()) {
throw new IllegalArgumentException("Export mapping is required");
}
String lineToWrite = "";
for (int i = 0; i < mapping.size(); i++) {
String propertyName = mapping.get(String.valueOf(i));
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.unomi.router.services;

import org.apache.unomi.api.Metadata;
import org.apache.unomi.api.Profile;
import org.apache.unomi.api.PropertyType;
import org.apache.unomi.router.api.ExportConfiguration;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.util.Collections;
import java.util.HashMap;
import java.util.Map;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

class ProfileExportServiceImplTest {

private ProfileExportServiceImpl profileExportService;

@BeforeEach
void setUp() {
profileExportService = new ProfileExportServiceImpl();
}

@Test
void extractProfilesBySegment_missingSegment_throwsIllegalArgumentException() {
ExportConfiguration configuration = new ExportConfiguration();
configuration.setProperty("mapping", Map.of("0", "firstName"));

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> profileExportService.extractProfilesBySegment(configuration));

assertEquals("Export segment is required", exception.getMessage());
}

@Test
void extractProfilesBySegment_blankSegment_throwsIllegalArgumentException() {
ExportConfiguration configuration = new ExportConfiguration();
configuration.setProperty("segment", " ");
configuration.setProperty("mapping", Map.of("0", "firstName"));

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> profileExportService.extractProfilesBySegment(configuration));

assertEquals("Export segment is required", exception.getMessage());
}

@Test
void extractProfilesBySegment_missingMapping_throwsIllegalArgumentException() {
ExportConfiguration configuration = new ExportConfiguration();
configuration.setProperty("segment", "frequent-buyers");

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> profileExportService.extractProfilesBySegment(configuration));

assertEquals("Export mapping is required", exception.getMessage());
}

@Test
void convertProfileToCSVLine_missingMapping_throwsIllegalArgumentException() {
ExportConfiguration configuration = new ExportConfiguration();
Profile profile = new Profile("profile-1");

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> profileExportService.convertProfileToCSVLine(profile, configuration, Collections.emptyList()));

assertEquals("Export mapping is required", exception.getMessage());
}

@Test
void convertProfileToCSVLine_nullPropertyValue_writesEmptyField() {
ExportConfiguration configuration = new ExportConfiguration();
configuration.setColumnSeparator(",");
Map<String, String> mapping = new HashMap<>();
mapping.put("0", "firstName");
configuration.setProperty("mapping", mapping);

Profile profile = new Profile("profile-1");
PropertyType propertyType = new PropertyType();
propertyType.setMetadata(new Metadata("firstName"));

String line = profileExportService.convertProfileToCSVLine(profile, configuration,
Collections.singletonList(propertyType));

assertTrue(line.isEmpty());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -293,9 +293,13 @@ private void testV2ModeBehavior() throws Exception {
try (CloseableHttpClient adminClient = HttpClients.custom()
.setDefaultCredentialsProvider(credsProvider)
.setDefaultRequestConfig(requestConfig)
.build();
CloseableHttpResponse jaasResponse = adminClient.execute(getRequest)) {
assertEquals("Private endpoint with JAAS auth should work in V2 compatibility mode", 200, jaasResponse.getStatusLine().getStatusCode());
.build()) {
try (CloseableHttpResponse jaasResponse = adminClient.execute(getRequest)) {
assertEquals("Private endpoint with JAAS auth should work in V2 compatibility mode", 200, jaasResponse.getStatusLine().getStatusCode());
}
try (CloseableHttpResponse privacyResponse = adminClient.execute(new HttpGet(getFullUrl("/cxs/privacy/info")))) {
assertEquals("GET /cxs/privacy/info with Karaf auth should work in V2 compatibility mode", 200, privacyResponse.getStatusLine().getStatusCode());
}
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1754,7 +1754,7 @@ public void setPropertyMapping(final PropertyType property, final String itemTyp
Map<String, Object> subSubMappings = (Map<String, Object>) subMappings.computeIfAbsent("properties", k -> new HashMap<>());

if (subSubMappings.containsKey(property.getItemId())) {
LOGGER.warn("Mapping already exists for type {} and property {}", itemType, property.getItemId());
LOGGER.debug("Mapping already exists for type {} and property {}", itemType, property.getItemId());
return;
}

Expand Down
15 changes: 15 additions & 0 deletions persistence-opensearch/core/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,21 @@
<artifactId>junit</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<scope>test</scope>
</dependency>

</dependencies>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -1711,7 +1711,7 @@ public void setPropertyMapping(final PropertyType property, final String itemTyp
Map<String, Object> subSubMappings = (Map<String, Object>) subMappings.computeIfAbsent("properties", k -> new HashMap<>());

if (subSubMappings.containsKey(property.getItemId())) {
LOGGER.warn("Mapping already exists for type " + itemType + " and property " + property.getItemId());
LOGGER.debug("Mapping already exists for type " + itemType + " and property " + property.getItemId());
return;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -241,6 +241,8 @@ private ObjectBuilder<FieldValue> getValue(Object fieldValue) {
return fieldValueBuilder.stringValue(convertDateToISO((Date) fieldValue).toString());
} else if (fieldValue instanceof OffsetDateTime) {
return fieldValueBuilder.stringValue(convertDateToISO((OffsetDateTime) fieldValue).toString());
} else if (fieldValue == null) {
throw new IllegalArgumentException("Impossible to build OS filter, unsupported value type: null");
} else {
throw new IllegalArgumentException("Impossible to build OS filter, unsupported value type: " + fieldValue.getClass().getName());
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.unomi.persistence.opensearch.querybuilders.core;

import org.apache.unomi.api.conditions.Condition;
import org.apache.unomi.persistence.opensearch.ConditionOSQueryBuilderDispatcher;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Arrays;
import java.util.Collections;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.junit.jupiter.api.Assertions.assertTrue;

@ExtendWith(MockitoExtension.class)
class PropertyConditionOSQueryBuilderTest {

@Mock
private ConditionOSQueryBuilderDispatcher dispatcher;

@Test
void buildQuery_inOperatorWithNullValue_throwsIllegalArgumentException() {
Condition condition = new Condition();
condition.setParameter("comparisonOperator", "in");
condition.setParameter("propertyName", "properties.firstName");
condition.setParameter("propertyValues", Arrays.asList("Jane", null));

PropertyConditionOSQueryBuilder builder = new PropertyConditionOSQueryBuilder();

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> builder.buildQuery(condition, Collections.emptyMap(), dispatcher));

assertTrue(exception.getMessage().contains("null"));
}

@Test
void buildQuery_equalsWithMissingValue_throwsIllegalArgumentException() {
Condition condition = new Condition();
condition.setParameter("comparisonOperator", "equals");
condition.setParameter("propertyName", "properties.firstName");

PropertyConditionOSQueryBuilder builder = new PropertyConditionOSQueryBuilder();

IllegalArgumentException exception = assertThrows(IllegalArgumentException.class,
() -> builder.buildQuery(condition, Collections.emptyMap(), dispatcher));

assertEquals("Impossible to build OS filter, missing value for condition using comparisonOperator: equals, and propertyName: properties.firstName",
exception.getMessage());
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,6 @@
import org.apache.karaf.jaas.boot.principal.UserPrincipal;
import org.apache.unomi.api.ExecutionContext;
import org.apache.unomi.api.security.SecurityService;
import org.apache.unomi.api.security.TenantPrincipal;
import org.apache.unomi.api.security.UnomiRoles;
import org.apache.unomi.api.services.ExecutionContextManager;
import org.apache.unomi.api.tenants.ApiKey;
Expand All @@ -47,7 +46,9 @@
import java.io.IOException;
import java.util.Base64;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
* A filter that combines JAAS authentication with tenant API key authentication:
Expand Down Expand Up @@ -310,14 +311,28 @@ private void handleV2CompatibilityMode(ContainerRequestContext requestContext, S
}
Subject jaasSubject = ((RolePrefixSecurityContextImpl) securityContext).getSubject();

// Build a merged subject that combines the JAAS principals with a TenantPrincipal
// for the default tenant, so that resolveTenantId() can find it downstream.
// Private endpoints in V2 compatibility mode require system administrator
// authentication (like V2) — a JAAS login alone isn't enough, since any Karaf
// user (not just admins) can authenticate against the realm.
if (!securityService.extractRolesFromSubject(jaasSubject).contains(UnomiRoles.ADMINISTRATOR)) {
logger.debug("V2 compatibility mode: authenticated user lacks administrator role, denying access to private endpoint");
unauthorized(requestContext);
return;
}

// Build a merged subject that combines the JAAS principals with tenant admin
// principals for the default tenant, so that resolveTenantId() can find it downstream.
String defaultTenantId = restAuthenticationConfig.getV2CompatibilityDefaultTenantId();
Subject mergedSubject = new Subject();
mergedSubject.getPrincipals().addAll(jaasSubject.getPrincipals());
if (StringUtils.isNotBlank(defaultTenantId)) {
mergedSubject.getPrincipals().add(new TenantPrincipal(defaultTenantId));
executionContextManager.setCurrentContext(executionContextManager.createContext(defaultTenantId));
mergedSubject.getPrincipals().addAll(securityService.createSubject(defaultTenantId, true).getPrincipals());
Set<String> roles = securityService.extractRolesFromSubject(mergedSubject);
Set<String> permissions = new HashSet<>();
for (String role : roles) {
permissions.addAll(securityService.getPermissionsForRole(role));
}
executionContextManager.setCurrentContext(new ExecutionContext(defaultTenantId, roles, permissions));
} else {
executionContextManager.setCurrentContext(ExecutionContext.systemContext());
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -281,6 +281,9 @@ public Collection<RESTValueType> getValueTypeByTag(@PathParam("tags") String tag
@Path("/values/{valueTypeId}")
public RESTValueType getValueType(@PathParam("valueTypeId") String id, @HeaderParam("Accept-Language") String language) {
ValueType valueType = definitionsService.getValueType(id);
if (valueType == null) {
throw new NotFoundException("Value type not found: " + id);
}
return localizationHelper.generateValueType(valueType, language);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@

import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.util.Set;

/**
Expand Down Expand Up @@ -72,8 +73,12 @@ public PartialList<Event> searchEvents(Query query) {
*/
@GET
@Path("/{id}")
public Event getEvents(@PathParam("id") final String id) {
return eventService.getEvent(id);
public Response getEvents(@PathParam("id") final String id) {
Event event = eventService.getEvent(id);
if (event == null) {
return Response.status(Response.Status.NOT_FOUND).build();
}
return Response.ok(event).build();
}

/**
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,9 @@ public void removeGoal(@PathParam("goalId") String goalId) {
@GET
@Path("/{goalID}/report")
public GoalReport getGoalReport(@PathParam("goalID") String goalId) {
if (goalsService.getGoal(goalId) == null) {
throw new NotFoundException("Goal not found: " + goalId);
}
return goalsService.getGoalReport(goalId);
}

Expand All @@ -136,6 +139,9 @@ public GoalReport getGoalReport(@PathParam("goalID") String goalId) {
@POST
@Path("/{goalID}/report")
public GoalReport getGoalReport(@PathParam("goalID") String goalId, AggregateQuery query) {
if (goalsService.getGoal(goalId) == null) {
throw new NotFoundException("Goal not found: " + goalId);
}
return goalsService.getGoalReport(goalId, query);
}
}
Loading
Loading