diff --git a/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterCriteria.java b/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterCriteria.java index 613408eb82..17fc6d059a 100644 --- a/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterCriteria.java +++ b/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterCriteria.java @@ -2,6 +2,8 @@ import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.DeviceType; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.packagesearch.PackageManagerType; import com.openframe.data.document.rmm.script.OsType; import lombok.AllArgsConstructor; @@ -31,6 +33,8 @@ public class DeviceFilterCriteria { private String pattern; private List hostnames; private List nicknames; + private List directorySources; + private List userLinks; public DeviceFilterCriteria(List statuses, List deviceTypes, List osTypes, List organizationIds, List tagKeys, List tagValues, diff --git a/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterFacet.java b/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterFacet.java index b0d9ba6f4d..5aacda947c 100644 --- a/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterFacet.java +++ b/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilterFacet.java @@ -22,12 +22,27 @@ public enum DeviceFilterFacet { OS_TYPES("osTypes"), ORGANIZATION_IDS("organizationIds"), TAG_KEYS("tagKeys"), + DIRECTORY_SOURCES("directorySources"), + USER_LINKS("userLinks"), FILTERED_COUNT("filteredCount"); - /** Every facet — the behaviour non-GraphQL callers (the external REST API) still want. */ + /** + * Every facet, the directory ones included. For a caller that has no selection set to narrow + * it and whose response can carry all of them. A caller whose response does not expose a + * facet must not use this: each unused facet is a Pinot round trip made for nothing. + */ public static final Set ALL = Collections.unmodifiableSet(EnumSet.allOf(DeviceFilterFacet.class)); + /** + * What the external REST {@code /filters} response carries: everything except the directory + * facets ({@link #DIRECTORY_SOURCES}, {@link #USER_LINKS}), which its DTO does not expose. + * Listed explicitly so a facet added later stays off the REST path until the DTO exposes it. + */ + public static final Set REST = + Collections.unmodifiableSet(EnumSet.of( + STATUSES, DEVICE_TYPES, OS_TYPES, ORGANIZATION_IDS, TAG_KEYS, FILTERED_COUNT)); + private final String graphQlField; DeviceFilterFacet(String graphQlField) { diff --git a/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilters.java b/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilters.java index 57d64989d4..47466f21a9 100644 --- a/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilters.java +++ b/openframe-api-lib/src/main/java/com/openframe/api/dto/device/DeviceFilters.java @@ -17,5 +17,7 @@ public class DeviceFilters { private List osTypes; private List organizationIds; private List tagKeys; + private List directorySources; + private List userLinks; private Integer filteredCount; } \ No newline at end of file diff --git a/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceFilterService.java b/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceFilterService.java index f6ddb1d88a..7becdf7a15 100644 --- a/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceFilterService.java +++ b/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceFilterService.java @@ -9,9 +9,11 @@ import com.openframe.data.service.TenantIdProvider; import lombok.extern.slf4j.Slf4j; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Set; @@ -20,11 +22,13 @@ import java.util.function.Supplier; import static com.openframe.api.dto.device.DeviceFilterFacet.DEVICE_TYPES; +import static com.openframe.api.dto.device.DeviceFilterFacet.DIRECTORY_SOURCES; import static com.openframe.api.dto.device.DeviceFilterFacet.FILTERED_COUNT; import static com.openframe.api.dto.device.DeviceFilterFacet.ORGANIZATION_IDS; import static com.openframe.api.dto.device.DeviceFilterFacet.OS_TYPES; import static com.openframe.api.dto.device.DeviceFilterFacet.STATUSES; import static com.openframe.api.dto.device.DeviceFilterFacet.TAG_KEYS; +import static com.openframe.api.dto.device.DeviceFilterFacet.USER_LINKS; import static java.util.Collections.emptyList; import static java.util.concurrent.CompletableFuture.completedFuture; import static java.util.concurrent.CompletableFuture.supplyAsync; @@ -33,25 +37,36 @@ @Slf4j public class DeviceFilterService { + private static final Set DIRECTORY_FACETS = EnumSet.of(DIRECTORY_SOURCES, USER_LINKS); + private final PinotDeviceRepository pinotDeviceRepository; private final DeviceFilterOptionMapper optionMapper; private final TenantIdProvider tenantIdProvider; private final Executor facetExecutor; + private final boolean directoryFacetsEnabled; + // The directory facets count values only an external directory integration writes. Without one (OSS) every + // machine reads as no source and NONE, so the two Pinot queries are skipped and the facets stay empty. The + // directory filters still apply either way. public DeviceFilterService(PinotDeviceRepository pinotDeviceRepository, DeviceFilterOptionMapper optionMapper, TenantIdProvider tenantIdProvider, @Qualifier(DeviceFilterExecutorConfig.DEVICE_FILTER_FACET_EXECUTOR) - Executor facetExecutor) { + Executor facetExecutor, + @Value("${openframe.device.directory-facets.enabled:false}") + boolean directoryFacetsEnabled) { this.pinotDeviceRepository = pinotDeviceRepository; this.optionMapper = optionMapper; this.tenantIdProvider = tenantIdProvider; this.facetExecutor = facetExecutor; + this.directoryFacetsEnabled = directoryFacetsEnabled; } /** - * Every facet. For callers with no selection set of their own — the external REST API, whose - * response DTO always carries all of them. + * Every facet ({@link DeviceFilterFacet#ALL}); the directory ones only while + * {@code openframe.device.directory-facets.enabled} is true, otherwise they come back empty. A + * caller whose response does not expose all of them should pass its own set instead, as the + * external REST API does with {@link DeviceFilterFacet#REST}. */ public CompletableFuture getDeviceFilters(DeviceFilterCriteria filters) { return getDeviceFilters(filters, DeviceFilterFacet.ALL); @@ -70,7 +85,7 @@ public CompletableFuture getDeviceFilters(DeviceFilterCriteria fi */ public CompletableFuture getDeviceFilters(DeviceFilterCriteria filters, Set requestedFacets) { - Set facets = requestedFacets != null ? requestedFacets : DeviceFilterFacet.ALL; + Set facets = queriedFacets(requestedFacets != null ? requestedFacets : DeviceFilterFacet.ALL); List statuses = filters != null && filters.getStatuses() != null ? filters.getStatuses().stream().map(Enum::name).toList() : emptyList(); List deviceTypes = filters != null && filters.getDeviceTypes() != null ? @@ -80,36 +95,55 @@ public CompletableFuture getDeviceFilters(DeviceFilterCriteria fi List organizationIds = filters != null ? filters.getOrganizationIds() : emptyList(); List tagKeys = filters != null ? filters.getTagKeys() : emptyList(); List tagKeyValues = buildTagKeyValuesFilter(filters); + List directorySources = filters != null && filters.getDirectorySources() != null ? + filters.getDirectorySources().stream().map(Enum::name).toList() : emptyList(); + List userLinks = filters != null && filters.getUserLinks() != null ? + filters.getUserLinks().stream().map(Enum::name).toList() : emptyList(); String tenantId = tenantIdProvider.getTenantId(); CompletableFuture> statusesFuture = facetQuery(facets, STATUSES, () -> - pinotDeviceRepository.getStatusFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues)); + pinotDeviceRepository.getStatusFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); CompletableFuture> deviceTypesFuture = facetQuery(facets, DEVICE_TYPES, () -> - pinotDeviceRepository.getDeviceTypeFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues)); + pinotDeviceRepository.getDeviceTypeFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); CompletableFuture> osTypesFuture = facetQuery(facets, OS_TYPES, () -> - pinotDeviceRepository.getOsTypeFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues)); + pinotDeviceRepository.getOsTypeFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); CompletableFuture> organizationsFuture = facetQuery(facets, ORGANIZATION_IDS, () -> - pinotDeviceRepository.getOrganizationFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues)); + pinotDeviceRepository.getOrganizationFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); CompletableFuture> tagKeysFuture = facetQuery(facets, TAG_KEYS, () -> - pinotDeviceRepository.getTagKeyFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues)); + pinotDeviceRepository.getTagKeyFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); + CompletableFuture> directorySourcesFuture = facetQuery(facets, DIRECTORY_SOURCES, () -> + pinotDeviceRepository.getDirectorySourceFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); + CompletableFuture> userLinksFuture = facetQuery(facets, USER_LINKS, () -> + pinotDeviceRepository.getUserLinkFilterOptions(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); CompletableFuture filteredCountFuture = facetQuery(facets, FILTERED_COUNT, () -> - pinotDeviceRepository.getFilteredDeviceCount(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues)); + pinotDeviceRepository.getFilteredDeviceCount(tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, directorySources, userLinks)); return CompletableFuture.allOf( - statusesFuture, deviceTypesFuture, osTypesFuture, - organizationsFuture, tagKeysFuture, filteredCountFuture) + statusesFuture, deviceTypesFuture, osTypesFuture, organizationsFuture, tagKeysFuture, + directorySourcesFuture, userLinksFuture, filteredCountFuture) .thenApply(v -> DeviceFilters.builder() .statuses(optionMapper.selfLabeled(statusesFuture.join())) .deviceTypes(optionMapper.selfLabeled(deviceTypesFuture.join())) .osTypes(optionMapper.selfLabeled(osTypesFuture.join())) .organizationIds(optionMapper.organizationLabeled(organizationsFuture.join())) .tagKeys(optionMapper.tagLabeled(tagKeysFuture.join())) + .directorySources(optionMapper.selfLabeled(directorySourcesFuture.join())) + .userLinks(optionMapper.selfLabeled(userLinksFuture.join())) .filteredCount(filteredCountFuture.join()) .build() ); } + private Set queriedFacets(Set requested) { + if (directoryFacetsEnabled || requested.isEmpty()) { + return requested; + } + EnumSet queried = EnumSet.copyOf(requested); + queried.removeAll(DIRECTORY_FACETS); + return queried; + } + /** * Submits one facet query, or short-circuits to {@code null} when the caller didn't ask for it. * diff --git a/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceService.java b/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceService.java index 9c13d712f1..7c5011525e 100644 --- a/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceService.java +++ b/openframe-api-lib/src/main/java/com/openframe/api/service/device/DeviceService.java @@ -38,7 +38,6 @@ import org.springframework.stereotype.Service; import org.springframework.validation.annotation.Validated; -import java.time.Instant; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -49,6 +48,7 @@ import java.util.stream.Collectors; import static com.openframe.data.service.machine.MachineFields.NICKNAME; +import static com.openframe.data.service.machine.MachineFields.STATUS; import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; @Service @@ -183,6 +183,9 @@ private DeviceFilters deviceFilters(MachineQueryFilter filter, String search) { .osTypes(deviceFilterOptionMapper.selfLabeled(machineRepository.facet(tenantId, filter, search, DeviceFacetDimension.OS_TYPE))) .organizationIds(deviceFilterOptionMapper.organizationLabeled(machineRepository.facet(tenantId, filter, search, DeviceFacetDimension.ORGANIZATION_ID))) .tagKeys(List.of()) + // The pickers' Mongo facets have no directory dimension: the two filters apply, their counts are [] + .directorySources(List.of()) + .userLinks(List.of()) .filteredCount((int) machineRepository.countMachines(tenantId, filter, search)) .build(); } @@ -275,7 +278,9 @@ private MachineQueryFilter machineFilter(DeviceFilterCriteria filter, .hostnames(filter.getHostnames()) .nicknames(filter.getNicknames()) .tagKeys(filter.getTagKeys()) - .tagValues(filter.getTagValues()); + .tagValues(filter.getTagValues()) + .directorySources(filter.getDirectorySources()) + .directoryUserLinks(filter.getUserLinks()); filterOsTypes = filter.getOsTypes(); } return builder.osTypes(resolveOsTypes(filterOsTypes, osTypeScope)) @@ -359,13 +364,14 @@ public void updateStatusByMachineId(@NotBlank String machineId, @NotNull DeviceS deviceSoftwareConnectivitySync.onConnectivityChanged(machine.getTenantId(), machineId, connected); } - machine.setStatus(status); - machine.setUpdatedAt(Instant.now()); - machineRepository.save(machine); + // Field-level: a whole-document save would overwrite what other writers set on the machine since the read + Machine updated = machineWriter.update(machineId, machineUpdate().set(STATUS, status)) + .map(MachineWriteResult::after) + .orElseThrow(() -> new DeviceNotFoundException("Device not found: " + machineId)); log.info("Device {} status updated to {}", machineId, status); try { - deviceStatusProcessor.postProcessStatusUpdated(machine); + deviceStatusProcessor.postProcessStatusUpdated(updated); } catch (Exception e) { log.error("Post-processor failed for machineId={}: {}", machineId, e.getMessage(), e); } diff --git a/openframe-api-lib/src/test/java/com/openframe/api/service/DeviceFilterServiceTest.java b/openframe-api-lib/src/test/java/com/openframe/api/service/DeviceFilterServiceTest.java index 7acda1bfdb..35ac126651 100644 --- a/openframe-api-lib/src/test/java/com/openframe/api/service/DeviceFilterServiceTest.java +++ b/openframe-api-lib/src/test/java/com/openframe/api/service/DeviceFilterServiceTest.java @@ -2,9 +2,12 @@ import com.openframe.api.dto.device.DeviceFilterCriteria; import com.openframe.api.dto.device.DeviceFilterFacet; +import com.openframe.api.dto.device.DeviceFilterOption; import com.openframe.api.dto.device.DeviceFilters; import com.openframe.api.mapper.DeviceFilterOptionMapper; import com.openframe.api.service.device.DeviceFilterService; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.pinot.repository.PinotDeviceRepository; import com.openframe.data.service.TenantIdProvider; import org.junit.jupiter.api.Test; @@ -23,6 +26,7 @@ import static com.openframe.data.document.rmm.script.OsType.MAC_OS; import static com.openframe.data.document.rmm.script.OsType.WINDOWS; import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.never; @@ -46,6 +50,10 @@ class DeviceFilterServiceTest { @Mock private com.openframe.data.repository.organization.OrganizationRepository organizationRepository; private DeviceFilterService service() { + return service(true); + } + + private DeviceFilterService service(boolean directoryFacetsEnabled) { when(tenantIdProvider.getTenantId()).thenReturn(TENANT); // Direct executor: the production pool is about wall-clock, not semantics, and running the // facet queries inline keeps assertion order deterministic. @@ -53,12 +61,13 @@ private DeviceFilterService service() { pinotDeviceRepository, new DeviceFilterOptionMapper(organizationRepository), tenantIdProvider, - Runnable::run); + Runnable::run, + directoryFacetsEnabled); } @Test void filteredCountOnly_runsOneQueryAndSkipsEveryFacet() { - when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any())) + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(7); DeviceFilters result = service() @@ -66,7 +75,7 @@ void filteredCountOnly_runsOneQueryAndSkipsEveryFacet() { .join(); assertThat(result.getFilteredCount()).isEqualTo(7); - verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); verifyNoMoreInteractions(pinotDeviceRepository); } @@ -87,9 +96,9 @@ void unrequestedFacetsAreEmptyListsNotNull() { @Test void dashboardCounterSelection_runsOnlyItsTwoQueries() { - when(pinotDeviceRepository.getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any())) + when(pinotDeviceRepository.getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(Map.of("ONLINE", 3)); - when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any())) + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(3); DeviceFilters result = service() @@ -100,46 +109,46 @@ void dashboardCounterSelection_runsOnlyItsTwoQueries() { assertThat(result.getStatuses()).hasSize(1); assertThat(result.getFilteredCount()).isEqualTo(3); verify(pinotDeviceRepository, never()) - .getDeviceTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); + .getDeviceTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); verify(pinotDeviceRepository, never()) - .getOsTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); + .getOsTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); verify(pinotDeviceRepository, never()) - .getOrganizationFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); + .getOrganizationFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); verify(pinotDeviceRepository, never()) - .getTagKeyFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); + .getTagKeyFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test void nullFacetSet_keepsTheOldAllFacetsBehaviour() { service().getDeviceFilters(DeviceFilterCriteria.builder().build(), null).join(); - verify(pinotDeviceRepository).getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); - verify(pinotDeviceRepository).getDeviceTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); - verify(pinotDeviceRepository).getOsTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); - verify(pinotDeviceRepository).getOrganizationFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); - verify(pinotDeviceRepository).getTagKeyFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); - verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getDeviceTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getOsTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getOrganizationFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getTagKeyFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test void singleArgOverload_stillRequestsEveryFacet() { service().getDeviceFilters(DeviceFilterCriteria.builder().build()).join(); - verify(pinotDeviceRepository).getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any()); - verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); } @Test void nullOsTypesCriteria_doesNotNpe_passesEmptyOsTypesToPinot() { @SuppressWarnings("unchecked") ArgumentCaptor> osTypes = ArgumentCaptor.forClass(List.class); - when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any())) + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(0); service().getDeviceFilters(DeviceFilterCriteria.builder().build(), Set.of(DeviceFilterFacet.FILTERED_COUNT)).join(); - verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), osTypes.capture(), any(), any(), any()); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), osTypes.capture(), any(), any(), any(), any(), any()); assertThat(osTypes.getValue()).isEmpty(); } @@ -147,13 +156,142 @@ void nullOsTypesCriteria_doesNotNpe_passesEmptyOsTypesToPinot() { void osTypesCriteria_mappedToEnumNamesForPinot() { @SuppressWarnings("unchecked") ArgumentCaptor> osTypes = ArgumentCaptor.forClass(List.class); - when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any())) + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) .thenReturn(0); service().getDeviceFilters(DeviceFilterCriteria.builder().osTypes(List.of(MAC_OS, WINDOWS)).build(), Set.of(DeviceFilterFacet.FILTERED_COUNT)).join(); - verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), osTypes.capture(), any(), any(), any()); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), osTypes.capture(), any(), any(), any(), any(), any()); assertThat(osTypes.getValue()).containsExactly("MAC_OS", "WINDOWS"); } + + @Test + void directoryColumnsSelection_runsOnlyTheirTwoQueries() { + when(pinotDeviceRepository.getDirectorySourceFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(Map.of("MICROSOFT_365", 4)); + when(pinotDeviceRepository.getUserLinkFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(Map.of("NONE", 9)); + + DeviceFilters result = service() + .getDeviceFilters(DeviceFilterCriteria.builder().build(), + EnumSet.of(DeviceFilterFacet.DIRECTORY_SOURCES, DeviceFilterFacet.USER_LINKS)) + .join(); + + assertThat(result.getDirectorySources()) + .extracting(DeviceFilterOption::getValue, DeviceFilterOption::getLabel, DeviceFilterOption::getCount) + .containsExactly(tuple("MICROSOFT_365", "MICROSOFT_365", 4)); + assertThat(result.getUserLinks()) + .extracting(DeviceFilterOption::getValue, DeviceFilterOption::getCount) + .containsExactly(tuple("NONE", 9)); + verify(pinotDeviceRepository).getDirectorySourceFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getUserLinkFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verifyNoMoreInteractions(pinotDeviceRepository); + } + + @Test + void unrequestedDirectoryFacetsAreEmptyListsNotNull() { + DeviceFilters result = service() + .getDeviceFilters(DeviceFilterCriteria.builder().build(), Set.of(DeviceFilterFacet.FILTERED_COUNT)) + .join(); + + assertThat(result.getDirectorySources()).isEmpty(); + assertThat(result.getUserLinks()).isEmpty(); + } + + @Test + void directoryCriteria_passedToPinotAsEnumNames() { + @SuppressWarnings("unchecked") + ArgumentCaptor> sources = ArgumentCaptor.forClass(List.class); + @SuppressWarnings("unchecked") + ArgumentCaptor> links = ArgumentCaptor.forClass(List.class); + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(0); + DeviceFilterCriteria criteria = DeviceFilterCriteria.builder() + .directorySources(List.of(DirectorySource.MICROSOFT_365)) + .userLinks(List.of(DirectoryUserLink.PRIMARY, DirectoryUserLink.NONE)) + .build(); + + service().getDeviceFilters(criteria, Set.of(DeviceFilterFacet.FILTERED_COUNT)).join(); + + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), + sources.capture(), links.capture()); + assertThat(sources.getValue()).containsExactly("MICROSOFT_365"); + assertThat(links.getValue()).containsExactly("PRIMARY", "NONE"); + } + + @Test + void nullDirectoryCriteria_passEmptyListsToPinot() { + @SuppressWarnings("unchecked") + ArgumentCaptor> sources = ArgumentCaptor.forClass(List.class); + @SuppressWarnings("unchecked") + ArgumentCaptor> links = ArgumentCaptor.forClass(List.class); + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(0); + + service().getDeviceFilters(DeviceFilterCriteria.builder().build(), Set.of(DeviceFilterFacet.FILTERED_COUNT)).join(); + + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), + sources.capture(), links.capture()); + assertThat(sources.getValue()).isEmpty(); + assertThat(links.getValue()).isEmpty(); + } + + @Test + void directoryFacetsDisabled_selectedDirectoryFacets_neverQueriedAndEmpty() { + when(pinotDeviceRepository.getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any())) + .thenReturn(5); + + DeviceFilters result = service(false) + .getDeviceFilters(DeviceFilterCriteria.builder().build(), EnumSet.of(DeviceFilterFacet.DIRECTORY_SOURCES, + DeviceFilterFacet.USER_LINKS, DeviceFilterFacet.FILTERED_COUNT)) + .join(); + + assertThat(result.getDirectorySources()).isEmpty(); + assertThat(result.getUserLinks()).isEmpty(); + assertThat(result.getFilteredCount()).isEqualTo(5); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verifyNoMoreInteractions(pinotDeviceRepository); + } + + @Test + void directoryFacetsDisabled_allFacets_runsEveryOtherQuery() { + service(false).getDeviceFilters(DeviceFilterCriteria.builder().build()).join(); + + verify(pinotDeviceRepository).getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getDeviceTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getOsTypeFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getOrganizationFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getTagKeyFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getFilteredDeviceCount(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository, never()).getDirectorySourceFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository, never()).getUserLinkFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void directoryFacetsDisabled_directoryCriteriaStillFilter() { + @SuppressWarnings("unchecked") + ArgumentCaptor> sources = ArgumentCaptor.forClass(List.class); + @SuppressWarnings("unchecked") + ArgumentCaptor> links = ArgumentCaptor.forClass(List.class); + DeviceFilterCriteria criteria = DeviceFilterCriteria.builder() + .directorySources(List.of(DirectorySource.MICROSOFT_365)) + .userLinks(List.of(DirectoryUserLink.SHARED)) + .build(); + + service(false).getDeviceFilters(criteria, Set.of(DeviceFilterFacet.STATUSES)).join(); + + verify(pinotDeviceRepository).getStatusFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), + sources.capture(), links.capture()); + assertThat(sources.getValue()).containsExactly("MICROSOFT_365"); + assertThat(links.getValue()).containsExactly("SHARED"); + } + + @Test + void directoryFacetsEnabled_allFacets_queriesTheDirectoryFacetsToo() { + service(true).getDeviceFilters(DeviceFilterCriteria.builder().build()).join(); + + verify(pinotDeviceRepository).getDirectorySourceFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + verify(pinotDeviceRepository).getUserLinkFilterOptions(anyString(), any(), any(), any(), any(), any(), any(), any(), any()); + } } diff --git a/openframe-api-service-core/src/main/java/com/openframe/api/datafetcher/DeviceDataFetcher.java b/openframe-api-service-core/src/main/java/com/openframe/api/datafetcher/DeviceDataFetcher.java index c50362845f..9fa4eeed13 100644 --- a/openframe-api-service-core/src/main/java/com/openframe/api/datafetcher/DeviceDataFetcher.java +++ b/openframe-api-service-core/src/main/java/com/openframe/api/datafetcher/DeviceDataFetcher.java @@ -29,6 +29,8 @@ import com.openframe.api.service.FleetVulnerabilityStatusService; import com.openframe.api.service.NotificationRecipientResolver; import com.openframe.api.service.TagService; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.installedagents.InstalledAgent; import com.openframe.data.document.organization.Organization; @@ -207,6 +209,24 @@ public boolean softwareManagementSupported(DgsDataFetchingEnvironment dfe) { return packageManagerAvailability.isSoftwareManageable(machine); } + @DgsData(parentType = "Machine") + public List directorySources(DgsDataFetchingEnvironment dfe) { + Machine machine = dfe.getSource(); + return mapper.toDirectorySources(machine); + } + + @DgsData(parentType = "Machine") + public DirectoryUserLink directoryUserLink(DgsDataFetchingEnvironment dfe) { + Machine machine = dfe.getSource(); + return mapper.toDirectoryUserLink(machine); + } + + @DgsData(parentType = "Machine") + public List directoryUserIds(DgsDataFetchingEnvironment dfe) { + Machine machine = dfe.getSource(); + return mapper.toDirectoryUserIds(machine); + } + // The current user's unread notifications about this device, batched for the whole page: the // same read states the sidebar badge counts, so a row and the badge agree. @DgsData(parentType = "Machine") diff --git a/openframe-api-service-core/src/main/java/com/openframe/api/dto/device/DeviceFilterInput.java b/openframe-api-service-core/src/main/java/com/openframe/api/dto/device/DeviceFilterInput.java index 5f88f4f2a3..83ea51ad9b 100644 --- a/openframe-api-service-core/src/main/java/com/openframe/api/dto/device/DeviceFilterInput.java +++ b/openframe-api-service-core/src/main/java/com/openframe/api/dto/device/DeviceFilterInput.java @@ -2,6 +2,8 @@ import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.DeviceType; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.rmm.script.OsType; import lombok.AllArgsConstructor; import lombok.Builder; @@ -21,4 +23,6 @@ public class DeviceFilterInput { private List organizationIds; private List tagKeys; private List tagValues; + private List directorySources; + private List userLinks; } \ No newline at end of file diff --git a/openframe-api-service-core/src/main/java/com/openframe/api/mapper/GraphQLDeviceMapper.java b/openframe-api-service-core/src/main/java/com/openframe/api/mapper/GraphQLDeviceMapper.java index dbb3789fce..3626ea60d3 100644 --- a/openframe-api-service-core/src/main/java/com/openframe/api/mapper/GraphQLDeviceMapper.java +++ b/openframe-api-service-core/src/main/java/com/openframe/api/mapper/GraphQLDeviceMapper.java @@ -10,6 +10,8 @@ import com.openframe.api.dto.shared.ConnectionArgs; import com.openframe.api.dto.shared.PageInfo; import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.packagesearch.PackageManagerState; import com.openframe.data.document.packagesearch.PackageManagerType; @@ -41,6 +43,8 @@ public DeviceFilterCriteria toDeviceFilterCriteria(DeviceFilterInput input) { .organizationIds(input.getOrganizationIds()) .tagKeys(input.getTagKeys()) .tagValues(input.getTagValues()) + .directorySources(input.getDirectorySources()) + .userLinks(input.getUserLinks()) .build(); } @@ -62,6 +66,23 @@ public MachinePackageManagersResponse toPackageManagers(Map toDirectorySources(Machine machine) { + List sources = machine.getDirectorySources(); + return sources != null ? sources : List.of(); + } + + public DirectoryUserLink toDirectoryUserLink(Machine machine) { + DirectoryUserLink link = machine.getDirectoryUserLink(); + return link != null ? link : DirectoryUserLink.NONE; + } + + public List toDirectoryUserIds(Machine machine) { + List userIds = machine.getDirectoryUserIds(); + return userIds != null ? userIds : List.of(); + } + public DeviceEnrollmentResponse toEnrollment(Machine machine, List toolConnections) { Instant connectedAt = machine.getFirstConnectedAt(); Instant inventoryConnectedAt = fleetInventoryConnectedAt(toolConnections); diff --git a/openframe-api-service-core/src/main/java/com/openframe/api/service/ForceClientUninstallService.java b/openframe-api-service-core/src/main/java/com/openframe/api/service/ForceClientUninstallService.java index 2398f522f5..0fc8ed5858 100644 --- a/openframe-api-service-core/src/main/java/com/openframe/api/service/ForceClientUninstallService.java +++ b/openframe-api-service-core/src/main/java/com/openframe/api/service/ForceClientUninstallService.java @@ -8,6 +8,7 @@ import com.openframe.data.nats.delivery.ClientUninstallDeliverySeed; import com.openframe.data.nats.delivery.route.DeliveryRouter; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineWriter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -17,6 +18,8 @@ import static com.openframe.data.document.device.DeviceStatus.DELETED; import static com.openframe.data.document.device.DeviceStatus.PENDING_DELETION; +import static com.openframe.data.service.machine.MachineFields.STATUS; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; import static org.apache.commons.lang3.ObjectUtils.isEmpty; @Service @@ -25,6 +28,7 @@ public class ForceClientUninstallService { private final MachineRepository machineRepository; + private final MachineWriter machineWriter; private final DeliveryRouter deliveryRouter; public ForceClientUninstallResponse process(ForceClientUninstallRequest request) { @@ -70,8 +74,7 @@ private void markPendingDeletion(Machine machine) { if (machine.getStatus() == PENDING_DELETION) { return; } - machine.setStatus(PENDING_DELETION); - machineRepository.save(machine); + machineWriter.update(machine.getMachineId(), machineUpdate().set(STATUS, PENDING_DELETION)); log.info("Machine {} marked PENDING_DELETION", machine.getMachineId()); } diff --git a/openframe-api-service-core/src/main/resources/schema/device.graphqls b/openframe-api-service-core/src/main/resources/schema/device.graphqls index 5f42d7a07f..1ce18bd5c3 100644 --- a/openframe-api-service-core/src/main/resources/schema/device.graphqls +++ b/openframe-api-service-core/src/main/resources/schema/device.graphqls @@ -24,6 +24,10 @@ type DeviceFilters { osTypes: [DeviceFilterOption!]! organizationIds: [DeviceFilterOption!]! tagKeys: [TagFilterOption!]! + """SOURCES filter options; [] in OSS, and on the schedule and bundle device pickers.""" + directorySources: [DeviceFilterOption!]! + """USER filter options: PRIMARY, SHARED, NONE. A machine without a directory link counts as NONE.""" + userLinks: [DeviceFilterOption!]! filteredCount: Int! } @@ -46,6 +50,10 @@ input DeviceFilterInput { organizationIds: [String!] tagKeys: [String!] tagValues: [String!] + """SOURCES filter: machines one of these directories knows. Matches nothing in OSS.""" + directorySources: [DirectorySource!] + """USER filter. NONE also matches a machine no external directory integration wrote (every machine in OSS).""" + userLinks: [DirectoryUserLink!] } type Machine implements Node @key(fields: "machineId") @shareable { @@ -82,6 +90,14 @@ type Machine implements Node @key(fields: "machineId") @shareable { from device pickers and skips it at dispatch; inventory and vulnerabilities still show it.""" softwareManagementSupported: Boolean! enrollment: DeviceEnrollment + """SOURCES column: the directories that know this machine besides the agent; [] when none, and always in OSS.""" + directorySources: [DirectorySource!]! + """USER column: who the machine is tied to; NONE when nobody, and always in OSS.""" + directoryUserLink: DirectoryUserLink! + """Account ids (DirectoryAccount.id) of the tied users, the primary user first. SHARED shows 'N recent users' with N = its length.""" + directoryUserIds: [String!]! + """Display name of the user for PRIMARY; null otherwise. devices(search) also matches it.""" + directoryUserName: String """The current user's unread notifications about this device (entity DEVICE, machineId). Counts the same read states as unreadCountsByCategory, so a row and the sidebar badge agree. 0 when none.""" unreadNotificationCount: Int! @@ -128,6 +144,19 @@ enum DeviceType { OTHER } +"""Who the machine is tied to. PRIMARY: one declared user. SHARED: several users, or recent users only. NONE: nobody.""" +enum DirectoryUserLink { + PRIMARY + SHARED + NONE +} + +"""A directory that knows the machine besides the agent.""" +enum DirectorySource { + MICROSOFT_365 + GOOGLE_WORKSPACE +} + type DeviceConnection { edges: [DeviceEdge!]! pageInfo: PageInfo! diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceDataFetcherTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceDataFetcherTest.java index 1a2a62a993..7e058553ad 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceDataFetcherTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceDataFetcherTest.java @@ -14,6 +14,8 @@ import com.openframe.data.document.notification.NotificationEntityType; import com.openframe.data.document.notification.RecipientType; import com.netflix.graphql.dgs.DgsDataFetchingEnvironment; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.tool.ToolConnection; import com.openframe.data.document.tool.ToolType; @@ -128,6 +130,21 @@ void enrollment_loadsToolConnectionsForTheMachineAndMaps() throws Exception { verify(mapper).toEnrollment(machine, connections); } + @Test + @DisplayName("directory fields: resolved through the mapper, so a null never reaches the non-null schema fields") + void directoryFields_resolvedThroughTheMapper() { + Machine machine = new Machine(); + machine.setMachineId("m1"); + when(dfe.getSource()).thenReturn(machine); + when(mapper.toDirectorySources(machine)).thenReturn(List.of(DirectorySource.MICROSOFT_365)); + when(mapper.toDirectoryUserLink(machine)).thenReturn(DirectoryUserLink.PRIMARY); + when(mapper.toDirectoryUserIds(machine)).thenReturn(List.of("acc-1")); + + assertThat(fetcher.directorySources(dfe)).containsExactly(DirectorySource.MICROSOFT_365); + assertThat(fetcher.directoryUserLink(dfe)).isEqualTo(DirectoryUserLink.PRIMARY); + assertThat(fetcher.directoryUserIds(dfe)).containsExactly("acc-1"); + } + @Test @DisplayName("unreadNotificationCount: loads the current user's count for (DEVICE, machineId) through the unread notification loader") void unreadNotificationCount_loadsTheCurrentUsersDeviceCountThroughTheLoader() throws Exception { diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceFiltersSelectionSetTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceFiltersSelectionSetTest.java index 5decf30b14..5623359690 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceFiltersSelectionSetTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/datafetcher/DeviceFiltersSelectionSetTest.java @@ -34,11 +34,13 @@ import java.util.concurrent.CompletableFuture; import static com.openframe.api.dto.device.DeviceFilterFacet.DEVICE_TYPES; +import static com.openframe.api.dto.device.DeviceFilterFacet.DIRECTORY_SOURCES; import static com.openframe.api.dto.device.DeviceFilterFacet.FILTERED_COUNT; import static com.openframe.api.dto.device.DeviceFilterFacet.ORGANIZATION_IDS; import static com.openframe.api.dto.device.DeviceFilterFacet.OS_TYPES; import static com.openframe.api.dto.device.DeviceFilterFacet.STATUSES; import static com.openframe.api.dto.device.DeviceFilterFacet.TAG_KEYS; +import static com.openframe.api.dto.device.DeviceFilterFacet.USER_LINKS; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; @@ -66,6 +68,8 @@ class DeviceFiltersSelectionSetTest { osTypes: [DeviceFilterOption] organizationIds: [DeviceFilterOption] tagKeys: [TagFilterOption] + directorySources: [DeviceFilterOption] + userLinks: [DeviceFilterOption] filteredCount: Int } type DeviceFilterOption { value: String label: String count: Int } @@ -139,9 +143,19 @@ void filterUiSelection_stillGetsEveryFacet() { osTypes { value count } organizationIds { value count } tagKeys { key value count } + directorySources { value count } + userLinks { value count } filteredCount } }""")) - .containsExactlyInAnyOrder(STATUSES, DEVICE_TYPES, OS_TYPES, ORGANIZATION_IDS, TAG_KEYS, FILTERED_COUNT); + .containsExactlyInAnyOrder(STATUSES, DEVICE_TYPES, OS_TYPES, ORGANIZATION_IDS, TAG_KEYS, + DIRECTORY_SOURCES, USER_LINKS, FILTERED_COUNT); + } + + @Test + void directoryColumnsSelection_narrowsToTheirTwoFacets() { + // The SOURCES and USER filters of the devices list ask for these two alone + assertThat(facetsFor("{ deviceFilters { directorySources { value count } userLinks { value count } } }")) + .containsExactlyInAnyOrder(DIRECTORY_SOURCES, USER_LINKS); } @Test diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/integration/service/MachineFieldLevelWritesIT.java b/openframe-api-service-core/src/test/java/com/openframe/api/integration/service/MachineFieldLevelWritesIT.java new file mode 100644 index 0000000000..a7edd67fbe --- /dev/null +++ b/openframe-api-service-core/src/test/java/com/openframe/api/integration/service/MachineFieldLevelWritesIT.java @@ -0,0 +1,164 @@ +package com.openframe.api.integration.service; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.openframe.api.dto.force.request.ForceClientUninstallRequest; +import com.openframe.api.mapper.DeviceFilterOptionMapper; +import com.openframe.api.service.ForceClientUninstallService; +import com.openframe.api.service.device.DeviceService; +import com.openframe.api.service.processor.DeviceStatusProcessor; +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; +import com.openframe.data.document.device.Machine; +import com.openframe.data.nats.delivery.route.DeliveryRouter; +import com.openframe.data.repository.device.CustomMachineRepositoryImpl; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.repository.tag.TagAssignmentRepository; +import com.openframe.data.repository.tag.TagRepository; +import com.openframe.data.service.TenantIdProvider; +import com.openframe.data.service.machine.MachineWriter; +import com.openframe.data.service.rmm.DeletedMachineCleanup; +import com.openframe.data.service.rmm.software.DeviceSoftwareConnectivitySync; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory; +import org.springframework.data.repository.core.support.RepositoryComposition.RepositoryFragments; +import org.testcontainers.mongodb.MongoDBContainer; +import org.testcontainers.utility.DockerImageName; + +import java.util.List; +import java.util.Optional; + +import static com.openframe.data.service.machine.MachineFields.COMPUTER_NAME; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_SOURCES; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_IDS; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_LINK; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_NAME; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +// The status writers read the machine, decide, then write. A $set an external directory integration (or the Fleet +// facts writer) makes between the read and the write must survive it. +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class MachineFieldLevelWritesIT { + + private static final String MACHINE_ID = "m-1"; + + private static final MongoDBContainer MONGO = new MongoDBContainer(DockerImageName.parse("mongo:7")); + + private static MongoClient client; + private static MongoTemplate template; + private static MachineRepository storedMachines; + private static MachineWriter machineWriter; + + private MachineRepository interleavingMachines; + + @BeforeAll + static void startMongo() { + String uri = System.getProperty("mongo.external.uri"); + if (uri == null) { + if (!MONGO.isRunning()) { + MONGO.start(); + } + uri = MONGO.getConnectionString() + "/?directConnection=true"; + } + client = MongoClients.create(uri); + template = new MongoTemplate(client, "test"); + storedMachines = new MongoRepositoryFactory(template).getRepository(MachineRepository.class, + RepositoryFragments.just(new CustomMachineRepositoryImpl(template))); + machineWriter = new MachineWriter(template, absent(), absent()); + } + + // Publishing off: no OutboxPublisher bean. + @SuppressWarnings("unchecked") + private static ObjectProvider absent() { + return mock(ObjectProvider.class); + } + + @AfterAll + static void stopMongo() { + client.close(); + } + + @BeforeEach + void setUp() { + template.dropCollection(Machine.class); + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + machine.setTenantId("tenant-1"); + machine.setStatus(DeviceStatus.ONLINE); + template.save(machine); + interleavingMachines = mock(MachineRepository.class, delegatesTo(storedMachines)); + doAnswer(invocation -> { + Optional read = storedMachines.findByMachineId(invocation.getArgument(0)); + concurrentDirectoryAndFleetWrite(); + return read; + }).when(interleavingMachines).findByMachineId(anyString()); + } + + @Test + void forceClientUninstall_concurrentDirectoryAndFleetSetAfterTheRead_survives() { + // setup + DeliveryRouter deliveryRouter = mock(DeliveryRouter.class); + when(deliveryRouter.dispatch(any())).thenReturn(true); + ForceClientUninstallService service = + new ForceClientUninstallService(interleavingMachines, machineWriter, deliveryRouter); + ForceClientUninstallRequest request = new ForceClientUninstallRequest(); + request.setMachineIds(List.of(MACHINE_ID)); + + // execution + service.process(request); + + // verifications + assertStatusWrittenAndConcurrentFieldsKept(DeviceStatus.PENDING_DELETION); + } + + @Test + void updateStatusByMachineId_concurrentDirectoryAndFleetSetAfterTheRead_survives() { + // setup + DeviceService service = new DeviceService(interleavingMachines, mock(DeletedMachineCleanup.class), + mock(DeviceSoftwareConnectivitySync.class), machineWriter, mock(TagRepository.class), + mock(TagAssignmentRepository.class), + mock(DeviceStatusProcessor.class), mock(DeviceFilterOptionMapper.class), + mock(TenantIdProvider.class), mock(ApplicationEventPublisher.class)); + + // execution + service.updateStatusByMachineId(MACHINE_ID, DeviceStatus.ARCHIVED); + + // verifications + assertStatusWrittenAndConcurrentFieldsKept(DeviceStatus.ARCHIVED); + } + + private static void assertStatusWrittenAndConcurrentFieldsKept(DeviceStatus expectedStatus) { + Machine stored = storedMachines.findByMachineId(MACHINE_ID).orElseThrow(); + assertThat(stored.getStatus()).isEqualTo(expectedStatus); + assertThat(stored).extracting(Machine::getDirectorySources, Machine::getDirectoryUserLink, + Machine::getDirectoryUserIds, Machine::getDirectoryUserName, Machine::getComputerName) + .containsExactly(List.of(DirectorySource.MICROSOFT_365), DirectoryUserLink.PRIMARY, + List.of("acc-1"), "Jane Doe", "Jane's MacBook Pro"); + } + + private static void concurrentDirectoryAndFleetWrite() { + machineWriter.update(MACHINE_ID, machineUpdate() + .set(DIRECTORY_SOURCES, List.of(DirectorySource.MICROSOFT_365)) + .set(DIRECTORY_USER_LINK, DirectoryUserLink.PRIMARY) + .set(DIRECTORY_USER_IDS, List.of("acc-1")) + .set(DIRECTORY_USER_NAME, "Jane Doe") + .set(COMPUTER_NAME, "Jane's MacBook Pro")); + } +} diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/mapper/GraphQLDeviceMapperTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/mapper/GraphQLDeviceMapperTest.java index 5d62853cbc..b8b222e78e 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/mapper/GraphQLDeviceMapperTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/mapper/GraphQLDeviceMapperTest.java @@ -1,6 +1,10 @@ package com.openframe.api.mapper; import com.openframe.api.dto.device.DeviceEnrollmentResponse; +import com.openframe.api.dto.device.DeviceFilterCriteria; +import com.openframe.api.dto.device.DeviceFilterInput; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.tool.ConnectionStatus; import com.openframe.data.document.tool.ToolConnection; @@ -119,4 +123,58 @@ void toEnrollment_readyOnlyWhenBothTimestampsSet() { assertThat(mapper.toEnrollment(machine(null), inventory).isReady()).as("inventory only").isFalse(); assertThat(mapper.toEnrollment(machine(null), List.of()).isReady()).as("neither").isFalse(); } + + @Test + @DisplayName("directorySources: a machine no directory integration wrote (every OSS machine) reads []") + void toDirectorySources_nullStored_emptyList() { + assertThat(mapper.toDirectorySources(machine(null))).isEmpty(); + } + + @Test + @DisplayName("directorySources: stored sources are returned as they are") + void toDirectorySources_stored_returned() { + Machine machine = machine(null); + machine.setDirectorySources(List.of(DirectorySource.MICROSOFT_365)); + + assertThat(mapper.toDirectorySources(machine)).containsExactly(DirectorySource.MICROSOFT_365); + } + + @Test + @DisplayName("directoryUserLink: a machine without a link reads NONE") + void toDirectoryUserLink_nullStored_none() { + assertThat(mapper.toDirectoryUserLink(machine(null))).isEqualTo(DirectoryUserLink.NONE); + } + + @Test + @DisplayName("directoryUserLink: a stored link is returned") + void toDirectoryUserLink_stored_returned() { + Machine machine = machine(null); + machine.setDirectoryUserLink(DirectoryUserLink.SHARED); + + assertThat(mapper.toDirectoryUserLink(machine)).isEqualTo(DirectoryUserLink.SHARED); + } + + @Test + @DisplayName("directoryUserIds: null reads [], stored ids keep their order (the primary user first)") + void toDirectoryUserIds_nullAndStored() { + Machine stored = machine(null); + stored.setDirectoryUserIds(List.of("acc-2", "acc-1")); + + assertThat(mapper.toDirectoryUserIds(machine(null))).isEmpty(); + assertThat(mapper.toDirectoryUserIds(stored)).containsExactly("acc-2", "acc-1"); + } + + @Test + @DisplayName("toDeviceFilterCriteria: the SOURCES and USER filters are copied from the input") + void toDeviceFilterCriteria_directoryFilters_copied() { + DeviceFilterInput input = DeviceFilterInput.builder() + .directorySources(List.of(DirectorySource.MICROSOFT_365)) + .userLinks(List.of(DirectoryUserLink.PRIMARY, DirectoryUserLink.NONE)) + .build(); + + DeviceFilterCriteria criteria = mapper.toDeviceFilterCriteria(input); + + assertThat(criteria.getDirectorySources()).containsExactly(DirectorySource.MICROSOFT_365); + assertThat(criteria.getUserLinks()).containsExactly(DirectoryUserLink.PRIMARY, DirectoryUserLink.NONE); + } } diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/schema/ApiSubgraphSchemaTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/schema/ApiSubgraphSchemaTest.java index d8de059dcc..cbfa00dcd5 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/schema/ApiSubgraphSchemaTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/schema/ApiSubgraphSchemaTest.java @@ -1,6 +1,8 @@ package com.openframe.api.schema; import com.apollographql.federation.graphqljava.Federation; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.ticket.TicketCreationSource; import com.openframe.data.document.ticket.TicketStatus; import graphql.ExecutionResult; @@ -11,6 +13,8 @@ import graphql.schema.GraphQLEnumType; import graphql.schema.GraphQLEnumValueDefinition; import graphql.schema.GraphQLFieldDefinition; +import graphql.schema.GraphQLInputObjectField; +import graphql.schema.GraphQLInputObjectType; import graphql.schema.GraphQLObjectType; import graphql.schema.GraphQLSchema; import graphql.schema.GraphQLTypeUtil; @@ -180,6 +184,71 @@ void ticketEnum_valuesEqualJavaEnum(String type, Class> javaEn assertThat(sdlNames).containsExactlyInAnyOrderElementsOf(javaNames); } + @ParameterizedTest + @MethodSource("machineDirectoryFields") + void machineDirectoryField_typedLikeTheContract(String field, String type) { + // setup + GraphQLFieldDefinition definition = schema.getObjectType("Machine").getFieldDefinition(field); + + // execution + String printed = GraphQLTypeUtil.simplePrint(definition.getType()); + + // verifications + assertThat(printed).isEqualTo(type); + } + + @Test + void machine_computerName_notExposed() { + // setup + GraphQLObjectType machine = schema.getObjectType("Machine"); + + // execution + GraphQLFieldDefinition computerName = machine.getFieldDefinition("computerName"); + + // verifications + assertThat(computerName).isNull(); + } + + @ParameterizedTest + @MethodSource("deviceFilterInputDirectoryFields") + void deviceFilterInputDirectoryField_typedLikeTheContract(String field, String type) { + // setup + GraphQLInputObjectType input = schema.getTypeAs("DeviceFilterInput"); + GraphQLInputObjectField definition = input.getFieldDefinition(field); + + // execution + String printed = GraphQLTypeUtil.simplePrint(definition.getType()); + + // verifications + assertThat(printed).isEqualTo(type); + } + + @ParameterizedTest + @ValueSource(strings = {"directorySources", "userLinks"}) + void deviceFiltersDirectoryFacet_nonNullOptionList(String field) { + // setup + GraphQLFieldDefinition definition = schema.getObjectType("DeviceFilters").getFieldDefinition(field); + + // execution + String printed = GraphQLTypeUtil.simplePrint(definition.getType()); + + // verifications + assertThat(printed).isEqualTo("[DeviceFilterOption!]!"); + } + + @ParameterizedTest + @MethodSource("directoryEnums") + void directoryEnum_valuesEqualJavaEnum(String type, Class> javaEnum) { + // setup + List javaNames = javaEnumNames(javaEnum); + + // execution + List sdlNames = sdlEnumNames(type); + + // verifications + assertThat(sdlNames).containsExactlyInAnyOrderElementsOf(javaNames); + } + @Test void entities_rootFieldAdded() { // execution @@ -210,6 +279,26 @@ private static Stream ticketEnums() { Arguments.of("TicketCreationSource", TicketCreationSource.class)); } + private static Stream machineDirectoryFields() { + return Stream.of( + Arguments.of("directorySources", "[DirectorySource!]!"), + Arguments.of("directoryUserLink", "DirectoryUserLink!"), + Arguments.of("directoryUserIds", "[String!]!"), + Arguments.of("directoryUserName", "String")); + } + + private static Stream deviceFilterInputDirectoryFields() { + return Stream.of( + Arguments.of("directorySources", "[DirectorySource!]"), + Arguments.of("userLinks", "[DirectoryUserLink!]")); + } + + private static Stream directoryEnums() { + return Stream.of( + Arguments.of("DirectorySource", DirectorySource.class), + Arguments.of("DirectoryUserLink", DirectoryUserLink.class)); + } + private static List sdlEnumNames(String type) { GraphQLEnumType definition = schema.getTypeAs(type); return definition.getValues().stream() diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceMachineSearchTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceMachineSearchTest.java index f034db8de0..c160005ef1 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceMachineSearchTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceMachineSearchTest.java @@ -1,6 +1,7 @@ package com.openframe.api.service; import com.openframe.api.dto.device.DeviceFilterCriteria; +import com.openframe.api.dto.device.DeviceFilters; import com.openframe.api.dto.CountedGenericQueryResult; import com.openframe.api.dto.shared.CursorPaginationCriteria; import com.openframe.api.mapper.DeviceFilterOptionMapper; @@ -9,6 +10,8 @@ import com.openframe.data.document.device.filter.MachineQueryFilter; import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.DeviceType; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.packagesearch.PackageManagerType; import com.openframe.data.document.rmm.script.OsType; @@ -75,6 +78,28 @@ void queryDevices_tagFilters_keepsRawTagsForTenantFencedQuery() { .containsExactly(List.of("environment"), List.of("production")); } + @Test + void queryDevices_directoryFilters_passedToTheMachineQuery() { + // setup + DeviceFilterCriteria filter = DeviceFilterCriteria.builder() + .directorySources(List.of(DirectorySource.MICROSOFT_365)) + .userLinks(List.of(DirectoryUserLink.NONE)).build(); + CursorPaginationCriteria pagination = CursorPaginationCriteria.builder().limit(10).build(); + when(tenantIdProvider.getTenantId()).thenReturn(TENANT_ID); + when(machineRepository.getDefaultSortField()).thenReturn("_id"); + when(machineRepository.findMachinesWithCursor(eq(TENANT_ID), any(MachineQueryFilter.class), isNull(), + isNull(), eq(11), eq("_id"), eq("DESC"))).thenReturn(List.of()); + + // execution + service.queryDevices(filter, pagination, null, null); + + // verifications + verify(machineRepository).countMachines(eq(TENANT_ID), filterCaptor.capture(), isNull()); + assertThat(filterCaptor.getValue()) + .extracting(MachineQueryFilter::getDirectorySources, MachineQueryFilter::getDirectoryUserLinks) + .containsExactly(List.of(DirectorySource.MICROSOFT_365), List.of(DirectoryUserLink.NONE)); + } + @Test void findDevicesAfter_sameFiltersAsDashboard_returnsSameMachinesAndPredicate() { // setup @@ -219,4 +244,17 @@ private Machine machine() { machine.setMachineId("machine-1"); return machine; } + + @Test + void getAssignedDeviceFilters_mongoFacets_directoryFacetsEmptyNotNull() { + // setup + DeviceFilterCriteria filter = DeviceFilterCriteria.builder().build(); + + // execution + DeviceFilters filters = service.getAssignedDeviceFilters(List.of("machine-1"), filter, null); + + // verifications + assertThat(filters.getDirectorySources()).isNotNull().isEmpty(); + assertThat(filters.getUserLinks()).isNotNull().isEmpty(); + } } diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceTest.java index 38e4a05f4f..1a7285540a 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/service/DeviceServiceTest.java @@ -291,6 +291,7 @@ void deletingDevice_cleansUpScheduleAssignments() { m.setTenantId("t-1"); m.setStatus(DeviceStatus.ONLINE); when(machineRepository.findByMachineId("m-del")).thenReturn(Optional.of(m)); + stubStatusWrite(m); service().updateStatusByMachineId("m-del", DeviceStatus.DELETED); @@ -313,6 +314,7 @@ void deletingDevice_cleanupFailsBeforeSave_statusStaysUnchanged() { .hasMessage("mongo hiccup"); verify(deletedMachineCleanup).cleanUpDeletedMachine("t-1", "m-del"); + verify(machineWriter, never()).update(any(), any(MachineUpdate.class)); verify(machineRepository, never()).save(any()); assertThat(m.getStatus()).isEqualTo(DeviceStatus.ONLINE); verifyNoInteractions(deviceStatusProcessor); @@ -326,6 +328,7 @@ void nonDeleteStatus_noAssignmentCleanup() { m.setTenantId("t-1"); m.setStatus(DeviceStatus.ONLINE); when(machineRepository.findByMachineId("m-off")).thenReturn(Optional.of(m)); + stubStatusWrite(m); service().updateStatusByMachineId("m-off", DeviceStatus.OFFLINE); @@ -340,6 +343,7 @@ void archiving_syncsConnectivityOff() { m.setTenantId("t-1"); m.setStatus(DeviceStatus.ONLINE); when(machineRepository.findByMachineId("m-arc")).thenReturn(Optional.of(m)); + stubStatusWrite(m); service().updateStatusByMachineId("m-arc", DeviceStatus.ARCHIVED); @@ -355,6 +359,7 @@ void restoringArchived_syncsConnectivityOn() { m.setTenantId("t-1"); m.setStatus(DeviceStatus.ARCHIVED); when(machineRepository.findByMachineId("m-arc")).thenReturn(Optional.of(m)); + stubStatusWrite(m); service().updateStatusByMachineId("m-arc", DeviceStatus.ONLINE); @@ -369,6 +374,7 @@ void onlineToOffline_noConnectivitySync() { m.setTenantId("t-1"); m.setStatus(DeviceStatus.ONLINE); when(machineRepository.findByMachineId("m-off")).thenReturn(Optional.of(m)); + stubStatusWrite(m); service().updateStatusByMachineId("m-off", DeviceStatus.OFFLINE); @@ -383,6 +389,7 @@ void deleting_usesCleanupNotConnectivitySync() { m.setTenantId("t-1"); m.setStatus(DeviceStatus.ONLINE); when(machineRepository.findByMachineId("m-del")).thenReturn(Optional.of(m)); + stubStatusWrite(m); service().updateStatusByMachineId("m-del", DeviceStatus.DELETED); @@ -390,6 +397,54 @@ void deleting_usesCleanupNotConnectivitySync() { verify(deviceSoftwareConnectivitySync, never()).onConnectivityChanged(any(), any(), anyBoolean()); } + @Test + @DisplayName("updateStatusByMachineId: writes only the status field and post-processes the stored result") + void statusChange_fieldLevelWrite_postProcessesTheWrittenMachine() { + Machine m = new Machine(); + m.setMachineId("m-off"); + m.setTenantId("t-1"); + m.setStatus(DeviceStatus.ONLINE); + when(machineRepository.findByMachineId("m-off")).thenReturn(Optional.of(m)); + stubStatusWrite(m); + + service().updateStatusByMachineId("m-off", DeviceStatus.OFFLINE); + + ArgumentCaptor update = ArgumentCaptor.forClass(MachineUpdate.class); + verify(machineWriter).update(eq("m-off"), update.capture()); + assertThat(update.getValue().paths()).containsExactly("status"); + ArgumentCaptor processed = ArgumentCaptor.forClass(Machine.class); + verify(deviceStatusProcessor).postProcessStatusUpdated(processed.capture()); + assertThat(processed.getValue().getStatus()).isEqualTo(DeviceStatus.OFFLINE); + verify(machineRepository, never()).save(any()); + } + + @Test + @DisplayName("updateStatusByMachineId: a device removed between the read and the write is not found") + void statusChange_deviceGoneBeforeTheWrite_notFound() { + Machine m = new Machine(); + m.setMachineId("m-off"); + m.setStatus(DeviceStatus.ONLINE); + when(machineRepository.findByMachineId("m-off")).thenReturn(Optional.of(m)); + when(machineWriter.update(eq("m-off"), any(MachineUpdate.class))).thenReturn(Optional.empty()); + + assertThatThrownBy(() -> service().updateStatusByMachineId("m-off", DeviceStatus.OFFLINE)) + .isInstanceOf(DeviceNotFoundException.class); + + verifyNoInteractions(deviceStatusProcessor); + } + + private void stubStatusWrite(Machine stored) { + when(machineWriter.update(eq(stored.getMachineId()), any(MachineUpdate.class))) + .thenAnswer(inv -> { + Machine after = new Machine(); + after.setMachineId(stored.getMachineId()); + after.setTenantId(stored.getTenantId()); + after.setStatus(stored.getStatus()); + inv.getArgument(1, MachineUpdate.class).applyTo(after); + return Optional.of(new MachineWriteResult(stored, after)); + }); + } + private void stubAtomicNicknameUpdate(String machineId) { when(machineWriter.update(eq(machineId), any(MachineUpdate.class))) diff --git a/openframe-api-service-core/src/test/java/com/openframe/api/service/ForceClientUninstallServiceTest.java b/openframe-api-service-core/src/test/java/com/openframe/api/service/ForceClientUninstallServiceTest.java index 7644af35b1..bf611204b8 100644 --- a/openframe-api-service-core/src/test/java/com/openframe/api/service/ForceClientUninstallServiceTest.java +++ b/openframe-api-service-core/src/test/java/com/openframe/api/service/ForceClientUninstallServiceTest.java @@ -8,6 +8,8 @@ import com.openframe.data.nats.delivery.ClientUninstallDeliverySeed; import com.openframe.data.nats.delivery.route.DeliveryRouter; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -22,6 +24,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -33,6 +37,8 @@ class ForceClientUninstallServiceTest { @Mock private MachineRepository machineRepository; @Mock private DeliveryRouter deliveryRouter; + @Mock private MachineWriter machineWriter; + @Captor private ArgumentCaptor updateCaptor; @Captor private ArgumentCaptor seedCaptor; @InjectMocks private ForceClientUninstallService service; @@ -60,8 +66,11 @@ void process_routeCarriesIt_sentAndMarkedPendingDeletion() { // verifications verify(deliveryRouter).dispatch(seedCaptor.capture()); assertThat(seedCaptor.getValue().getMachineId()).isEqualTo(MACHINE_ID); + verify(machineWriter).update(eq(MACHINE_ID), updateCaptor.capture()); + assertThat(updateCaptor.getValue().paths()).containsExactly("status"); + updateCaptor.getValue().applyTo(machine); assertThat(machine.getStatus()).isEqualTo(DeviceStatus.PENDING_DELETION); - verify(machineRepository).save(machine); + verify(machineRepository, never()).save(any()); assertThat(response.getItems().get(0).getStatus()).isEqualTo(ForceAgentStatus.PROCESSED); } @@ -74,8 +83,7 @@ void process_noRouteReachesTheMachine_failedAndStatusLeftAlone() { ForceClientUninstallResponse response = service.process(request); // verifications - assertThat(machine.getStatus()).isEqualTo(DeviceStatus.ONLINE); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); assertThat(response.getItems().get(0).getStatus()).isEqualTo(ForceAgentStatus.FAILED); } diff --git a/openframe-client-core/pom.xml b/openframe-client-core/pom.xml index 69d92f1198..5579cdcaa0 100644 --- a/openframe-client-core/pom.xml +++ b/openframe-client-core/pom.xml @@ -127,6 +127,11 @@ testcontainers-junit-jupiter test + + org.testcontainers + testcontainers-mongodb + test + diff --git a/openframe-client-core/src/main/java/com/openframe/client/scheduler/FleetHostFactsBackfillScheduler.java b/openframe-client-core/src/main/java/com/openframe/client/scheduler/FleetHostFactsBackfillScheduler.java new file mode 100644 index 0000000000..f3dedae89f --- /dev/null +++ b/openframe-client-core/src/main/java/com/openframe/client/scheduler/FleetHostFactsBackfillScheduler.java @@ -0,0 +1,36 @@ +package com.openframe.client.scheduler; + +import com.openframe.client.service.agentregistration.fleet.FleetHostFactsBackfillService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import net.javacrumbs.shedlock.spring.annotation.SchedulerLock; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +// Once an hour: fills the hardware facts Fleet knows (serial, computer name, model, manufacturer, OS UUID) of machines +// the tool connection consumer left without them: machines registered before Fleet facts were stored, and a fill that +// failed because the consumer or Fleet was down. A machine Fleet could not fill is tried again after +// openframe.fleet.host-facts.backfill.recheck-after (7 days by default). New machines are filled at once, when their +// Fleet connection is added. +@Component +@RequiredArgsConstructor +@Slf4j +@ConditionalOnProperty(name = "openframe.fleet.host-facts.backfill.enabled", havingValue = "true", matchIfMissing = true) +public class FleetHostFactsBackfillScheduler { + + private final FleetHostFactsBackfillService backfillService; + + @Scheduled(cron = "${openframe.fleet.host-facts.backfill.cron:0 15 * * * *}", zone = "UTC") + @SchedulerLock(name = "fleetHostFactsBackfill", + lockAtMostFor = "${openframe.fleet.host-facts.backfill.lock-at-most-for:1h}", + lockAtLeastFor = "${openframe.fleet.host-facts.backfill.lock-at-least-for:5m}") + public void run() { + try { + log.debug("Running Fleet host facts backfill"); + backfillService.backfill(); + } catch (Exception e) { + log.error("Fleet host facts backfill failed", e); + } + } +} diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/AgentUninstallService.java b/openframe-client-core/src/main/java/com/openframe/client/service/AgentUninstallService.java index 251130d016..7c16369c21 100644 --- a/openframe-client-core/src/main/java/com/openframe/client/service/AgentUninstallService.java +++ b/openframe-client-core/src/main/java/com/openframe/client/service/AgentUninstallService.java @@ -7,6 +7,8 @@ import com.openframe.data.document.oauth.OAuthClient; import com.openframe.data.repository.device.MachineRepository; import com.openframe.data.repository.oauth.OAuthClientRepository; +import com.openframe.data.service.machine.MachineWriteResult; +import com.openframe.data.service.machine.MachineWriter; import com.openframe.data.service.rmm.DeletedMachineCleanup; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -15,6 +17,9 @@ import java.util.Optional; +import static com.openframe.data.service.machine.MachineFields.STATUS; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; + @Service @RequiredArgsConstructor @Slf4j @@ -23,6 +28,7 @@ public class AgentUninstallService { private final OAuthClientRepository oauthClientRepository; private final ClientSecretValidator clientSecretValidator; private final MachineRepository machineRepository; + private final MachineWriter machineWriter; private final ToolConnectionService toolConnectionService; private final InstalledAgentService installedAgentService; private final DeletedMachineCleanup deletedMachineCleanup; @@ -42,14 +48,18 @@ public void uninstall(String machineId, String clientSecret) { return; } - Machine machine = foundMachine.get(); - if (machine.getStatus() == DeviceStatus.DELETED) { + if (foundMachine.get().getStatus() == DeviceStatus.DELETED) { log.info("Machine {} is already deleted, uninstall is a no-op", machineId); return; } - machine.setStatus(DeviceStatus.DELETED); - machineRepository.save(machine); + Optional deleted = machineWriter.update(machineId, machineUpdate().set(STATUS, DeviceStatus.DELETED)) + .map(MachineWriteResult::after); + if (deleted.isEmpty()) { + log.info("Machine {} document is gone, treating as already deregistered", machineId); + return; + } + Machine machine = deleted.get(); toolConnectionService.disconnectAll(machineId); installedAgentService.disconnectAll(machineId); diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/MachineHostnameService.java b/openframe-client-core/src/main/java/com/openframe/client/service/MachineHostnameService.java index 4e775f930e..3aa3f9871f 100644 --- a/openframe-client-core/src/main/java/com/openframe/client/service/MachineHostnameService.java +++ b/openframe-client-core/src/main/java/com/openframe/client/service/MachineHostnameService.java @@ -3,18 +3,23 @@ import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.Machine; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineWriter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import java.util.Optional; +import static com.openframe.data.service.machine.MachineFields.HOSTNAME; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; + @Service @RequiredArgsConstructor @Slf4j public class MachineHostnameService { private final MachineRepository machineRepository; + private final MachineWriter machineWriter; public void updateHostname(String machineId, String hostname) { Optional foundMachine = machineRepository.findByMachineId(machineId); @@ -35,8 +40,7 @@ public void updateHostname(String machineId, String hostname) { return; } - machine.setHostname(hostname); - machineRepository.save(machine); + machineWriter.update(machineId, machineUpdate().set(HOSTNAME, hostname)); log.info("Updated hostname for machineId={} to {}", machineId, hostname); } diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/MachineStatusService.java b/openframe-client-core/src/main/java/com/openframe/client/service/MachineStatusService.java index 912fbdb35c..1445c553ed 100644 --- a/openframe-client-core/src/main/java/com/openframe/client/service/MachineStatusService.java +++ b/openframe-client-core/src/main/java/com/openframe/client/service/MachineStatusService.java @@ -7,9 +7,13 @@ import com.openframe.data.document.device.Machine; import com.openframe.data.document.device.TelemetryStatus; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriteResult; +import com.openframe.data.service.machine.MachineWriter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.stereotype.Service; import java.time.Instant; @@ -17,6 +21,11 @@ import static com.openframe.data.document.device.DeviceStatus.OFFLINE; import static com.openframe.data.document.device.DeviceStatus.ONLINE; import static com.openframe.data.document.device.DeviceStatus.PENDING; +import static com.openframe.data.service.machine.MachineFields.FIRST_CONNECTED_AT; +import static com.openframe.data.service.machine.MachineFields.LAST_SEEN; +import static com.openframe.data.service.machine.MachineFields.STATUS; +import static com.openframe.data.service.machine.MachineFields.TELEMETRY_STATUS; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; @Service @RequiredArgsConstructor @@ -24,6 +33,7 @@ public class MachineStatusService { private final MachineRepository machineRepository; + private final MachineWriter machineWriter; private final ApplicationEventPublisher eventPublisher; public void updateToOnline(String machineId, Instant eventTimestamp) { @@ -74,36 +84,55 @@ private void applyStatusUpdate(Machine machine, DeviceStatus newStatus, Telemetr return; } boolean firstConnect = previousStatus == PENDING && (newStatus == ONLINE || newStatus == OFFLINE); - machine.setStatus(newStatus); - machine.setTelemetryStatus(telemetry); - machine.setLastSeen(eventTimestamp); + MachineUpdate update = machineUpdate() + .set(STATUS, newStatus) + .set(TELEMETRY_STATUS, telemetry) + .set(LAST_SEEN, eventTimestamp); if (firstConnect && machine.getFirstConnectedAt() == null) { - machine.setFirstConnectedAt(eventTimestamp); + update.set(FIRST_CONNECTED_AT, eventTimestamp); } - machineRepository.save(machine); - log.debug("Updated machineId={} to status={} at {}", machine.getMachineId(), newStatus, eventTimestamp); + // The transition only lands while the status is still the one it was decided from, so an uninstall or a + // status change that landed since the read is not overwritten + machineWriter.update(machine.getMachineId(), Criteria.where(STATUS.path()).is(previousStatus), update) + .map(MachineWriteResult::after) + .ifPresentOrElse( + updated -> announceTransition(updated, previousStatus, newStatus, firstConnect, eventTimestamp), + () -> recordPresenceOnly(machine, previousStatus, newStatus, telemetry, eventTimestamp)); + } + + // The status is no longer this event's to change, but the device was still heard from: its presence lands + private void recordPresenceOnly(Machine machine, DeviceStatus previousStatus, DeviceStatus newStatus, + TelemetryStatus telemetry, Instant eventTimestamp) { + log.info("Status of machineId={} changed since it was read, {} -> {} not applied, presence recorded", + machine.getMachineId(), previousStatus, newStatus); + touchPresence(machine, telemetry, eventTimestamp); + } + + private void announceTransition(Machine updated, DeviceStatus previousStatus, DeviceStatus newStatus, + boolean firstConnect, Instant eventTimestamp) { + log.debug("Updated machineId={} to status={} at {}", updated.getMachineId(), newStatus, eventTimestamp); if (firstConnect) { - log.info("Device first connected: machineId={}, transition {} -> {}", machine.getMachineId(), previousStatus, newStatus); - eventPublisher.publishEvent(new DeviceFirstConnectedEvent(this, machine)); + log.info("Device first connected: machineId={}, transition {} -> {}", updated.getMachineId(), previousStatus, newStatus); + eventPublisher.publishEvent(new DeviceFirstConnectedEvent(this, updated)); } if (previousStatus == OFFLINE && newStatus == ONLINE) { - log.info("Device came online (offline->online): machineId={}", machine.getMachineId()); - eventPublisher.publishEvent(new DeviceCameOnlineEvent(this, machine)); + log.info("Device came online (offline->online): machineId={}", updated.getMachineId()); + eventPublisher.publishEvent(new DeviceCameOnlineEvent(this, updated)); } } /** - * A heartbeat that changes nothing but lastSeen stays out of {@code save}: nothing that reaches Pinot has changed, - * and {@code save} would make the publishing aspect emit a duplicate message for every heartbeat. A connectivity - * flip is a real change and goes through {@code save}. + * A heartbeat that changes nothing but lastSeen stays out of {@code MachineWriter}: nothing that reaches Pinot has + * changed, and the writer would make the publishing aspect emit a duplicate message for every heartbeat. A + * connectivity flip is a real change and goes through {@code MachineWriter}. */ private void touchPresence(Machine machine, TelemetryStatus telemetry, Instant eventTimestamp) { if (machine.getTelemetryStatus() != telemetry) { - machine.setTelemetryStatus(telemetry); - machine.setLastSeen(eventTimestamp); - machineRepository.save(machine); + write(machine.getMachineId(), machineUpdate() + .set(TELEMETRY_STATUS, telemetry) + .set(LAST_SEEN, eventTimestamp)); log.debug("Updated machineId={} to telemetry={} at {} (status unchanged: {})", machine.getMachineId(), telemetry, eventTimestamp, machine.getStatus()); return; @@ -113,6 +142,11 @@ private void touchPresence(Machine machine, TelemetryStatus telemetry, Instant e machine.getMachineId(), eventTimestamp, machine.getStatus()); } + // Field-level: a whole-document save would overwrite what other writers set on the machine since it was read + private void write(String machineId, MachineUpdate update) { + machineWriter.update(machineId, update); + } + private void logStaleEvent(Machine machine, Instant eventTimestamp) { log.warn("Ignored stale event for machineId={} eventTimestamp={} lastSeen={} currentStatus={}", machine.getMachineId(), diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/MachineTimezoneService.java b/openframe-client-core/src/main/java/com/openframe/client/service/MachineTimezoneService.java index 8f97a7316c..bcb134e06b 100644 --- a/openframe-client-core/src/main/java/com/openframe/client/service/MachineTimezoneService.java +++ b/openframe-client-core/src/main/java/com/openframe/client/service/MachineTimezoneService.java @@ -3,6 +3,7 @@ import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.Machine; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineWriter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -12,6 +13,8 @@ import java.util.Optional; import java.util.Set; +import static com.openframe.data.service.machine.MachineFields.TIMEZONE; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; import static org.apache.commons.lang3.StringUtils.isBlank; @Service @@ -22,6 +25,7 @@ public class MachineTimezoneService { private static final Set AVAILABLE_ZONES = ZoneId.getAvailableZoneIds(); private final MachineRepository machineRepository; + private final MachineWriter machineWriter; public void updateTimezone(String machineId, String timezone) { if (isBlank(timezone)) { @@ -51,8 +55,7 @@ public void updateTimezone(String machineId, String timezone) { return; } - machine.setTimezone(timezone); - machineRepository.save(machine); + machineWriter.update(machineId, machineUpdate().set(TIMEZONE, timezone)); log.info("Updated timezone for machineId={} to {}", machineId, timezone); } diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/AgentRegistrationService.java b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/AgentRegistrationService.java index 40301ca9be..83c773a2fd 100644 --- a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/AgentRegistrationService.java +++ b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/AgentRegistrationService.java @@ -15,6 +15,10 @@ import com.openframe.data.document.rmm.script.OsType; import com.openframe.data.repository.device.MachineRepository; import com.openframe.data.repository.oauth.OAuthClientRepository; +import com.openframe.data.service.machine.MachineField; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriteResult; +import com.openframe.data.service.machine.MachineWriter; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.crypto.password.PasswordEncoder; @@ -26,6 +30,19 @@ import static com.openframe.client.service.AgentAuthService.CLIENT_CREDENTIALS_GRANT_TYPE; import static com.openframe.core.exception.ErrorCode.CLIENT_SECRET_INVALID; +import static com.openframe.data.service.machine.MachineFields.AGENT_VERSION; +import static com.openframe.data.service.machine.MachineFields.HOSTNAME; +import static com.openframe.data.service.machine.MachineFields.LAST_SEEN; +import static com.openframe.data.service.machine.MachineFields.MANUFACTURER; +import static com.openframe.data.service.machine.MachineFields.MODEL; +import static com.openframe.data.service.machine.MachineFields.ORGANIZATION_ID; +import static com.openframe.data.service.machine.MachineFields.OS_TYPE; +import static com.openframe.data.service.machine.MachineFields.OS_UUID; +import static com.openframe.data.service.machine.MachineFields.SERIAL_NUMBER; +import static com.openframe.data.service.machine.MachineFields.STATUS; +import static com.openframe.data.service.machine.MachineFields.TIMEZONE; +import static com.openframe.data.service.machine.MachineFields.USER_ID; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; import static java.lang.String.format; import static org.apache.commons.lang3.StringUtils.isNotBlank; @@ -41,6 +58,7 @@ public class AgentRegistrationService { private final OAuthClientRepository oauthClientRepository; private final MachineRepository machineRepository; + private final MachineWriter machineWriter; private final OrganizationIdResolver organizationIdResolver; private final AgentRegistrationSecretValidator secretValidator; private final ClientSecretValidator clientSecretValidator; @@ -72,11 +90,6 @@ public AgentRegistrationResponse register(String initialKey, AgentRegistrationRe return new AgentRegistrationResponse(machineId, clientId, clientSecret); } - private Machine loadMachine(String machineId) { - return machineRepository.findByMachineId(machineId) - .orElseThrow(() -> new IllegalStateException("Machine not found for registered client: " + machineId)); - } - private String buildClientId(String machineId) { return format(CLIENT_ID_TEMPLATE, machineId); } @@ -100,7 +113,7 @@ private void createOAuthClient(String machineId, String clientId, String clientS private Machine createMachine(String machineId, AgentRegistrationRequest request, String organizationId) { Machine machine = new Machine(); machine.setMachineId(machineId); - applyRegistrationRequestFields(machine, request); + registrationRequestFields(request).applyTo(machine); machine.setStatus(DeviceStatus.PENDING); machine.setOrganizationId(organizationId); machine.setType(DeviceType.DESKTOP); @@ -120,8 +133,7 @@ public AgentRegistrationResponse reinstall(String initialKey, String machineId, log.info("Reinstall for existing machine {}", machineId); - Machine machine = loadMachine(machineId); - updateMachine(machine, request); + Machine machine = updateMachine(machineId, request); toolConnectionService.disconnectAll(machineId); installedAgentService.disconnectAll(machineId); postProcessMachine(machine, request); @@ -155,30 +167,48 @@ private void saveInstalledAgent(String machineId, AgentRegistrationRequest reque installedAgentService.addInstalledAgent(machineId, OPENFRAME_CLIENT_AGENT_TYPE, agentVersion, false); } - private void updateMachine(Machine machine, AgentRegistrationRequest request) { - applyRegistrationRequestFields(machine, request); - machine.setStatus(DeviceStatus.PENDING); - + // Field-level: the machine already exists, and a whole-document save would overwrite what other writers set on it + // (the directory summary, Fleet hardware facts) since it was read + private Machine updateMachine(String machineId, AgentRegistrationRequest request) { + MachineUpdate update = registrationRequestFields(request).set(STATUS, DeviceStatus.PENDING); String organizationId = organizationIdResolver.resolve(request.getOrganizationId()); - machine.setOrganizationId(organizationId); + update.set(ORGANIZATION_ID, organizationId); - machineRepository.save(machine); + Machine machine = machineWriter.update(machineId, update) + .map(MachineWriteResult::after) + .orElseThrow(() -> new IllegalStateException("Machine not found for registered client: " + machineId)); - String machineId = machine.getMachineId(); log.info("Updated machine {} on reinstall, organizationId {}", machineId, organizationId); + return machine; } - private void applyRegistrationRequestFields(Machine machine, AgentRegistrationRequest request) { - machine.setHostname(request.getHostname()); - machine.setOsType(normalizeOsType(request.getOsType())); - machine.setAgentVersion(request.getAgentVersion()); - machine.setLastSeen(Instant.now()); + private MachineUpdate registrationRequestFields(AgentRegistrationRequest request) { + MachineUpdate update = machineUpdate() + .set(HOSTNAME, request.getHostname()) + .set(OS_TYPE, normalizeOsType(request.getOsType())) + .set(AGENT_VERSION, request.getAgentVersion()) + .set(LAST_SEEN, Instant.now()); // Optional; keep the existing value on reinstall when the agent doesn't send it - if (isNotBlank(request.getUserId())) { - machine.setUserId(request.getUserId()); - } + setIfNotBlank(update, USER_ID, request.getUserId()); if (isNotBlank(request.getTimezone()) && isValidZone(request.getTimezone())) { - machine.setTimezone(request.getTimezone()); + update.set(TIMEZONE, request.getTimezone()); + } + copyHardwareFacts(update, request); + return update; + } + + // Optional like userId: a fact the agent does not send keeps the stored value, and Fleet fills what is still + // blank once it knows the host (FleetHostFactsWriter) + private static void copyHardwareFacts(MachineUpdate update, AgentRegistrationRequest request) { + setIfNotBlank(update, SERIAL_NUMBER, request.getSerialNumber()); + setIfNotBlank(update, MANUFACTURER, request.getManufacturer()); + setIfNotBlank(update, MODEL, request.getModel()); + setIfNotBlank(update, OS_UUID, request.getOsUuid()); + } + + private static void setIfNotBlank(MachineUpdate update, MachineField field, String value) { + if (isNotBlank(value)) { + update.set(field, value); } } diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsBackfillService.java b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsBackfillService.java new file mode 100644 index 0000000000..fdf519a11f --- /dev/null +++ b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsBackfillService.java @@ -0,0 +1,135 @@ +package com.openframe.client.service.agentregistration.fleet; + +import com.openframe.data.document.device.Machine; +import com.openframe.data.document.tool.ConnectionStatus; +import com.openframe.data.document.tool.ToolConnection; +import com.openframe.data.document.tool.ToolType; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.repository.tool.ToolConnectionRepository; +import com.openframe.data.service.TenantIdProvider; +import com.openframe.sdk.fleetmdm.FleetMdmClient; +import com.openframe.sdk.fleetmdm.model.Host; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.time.Instant; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.apache.commons.lang3.StringUtils.isNumeric; + +// Fills the hardware facts Fleet knows (serial, computer name, model, manufacturer, OS UUID) where the tool connection +// consumer did not: machines registered before Fleet facts were stored, a fill that failed, a host Fleet had no facts +// for yet. One query picks the machines missing a fact that are due a check, at most MACHINES_PER_RUN, so a run costs +// as much as the machines left to fill, not the fleet. Every completed Fleet read is stamped on the machine (a read +// that threw is not), and so is a machine without a confirmed Fleet host: a machine is tried again only once the stamp +// is older than recheck-after, so machines Fleet cannot fill (a VM without a serial) do not use up the runs. +@Service +@RequiredArgsConstructor +@Slf4j +public class FleetHostFactsBackfillService { + + static final int MACHINES_PER_RUN = 200; + + private final MachineRepository machineRepository; + private final ToolConnectionRepository toolConnectionRepository; + private final FleetMdmClients fleetMdmClients; + private final FleetHostFactsWriter fleetHostFactsWriter; + private final TenantIdProvider tenantIdProvider; + + @Value("${openframe.fleet.host-facts.backfill.recheck-after:7d}") + private Duration recheckAfter; + + public void backfill() { + Instant now = Instant.now(); + String tenantId = tenantIdProvider.getTenantId(); + List due = machineRepository.findDueForFleetHostFacts(tenantId, now.minus(recheckAfter), MACHINES_PER_RUN); + if (due.isEmpty()) { + log.debug("Fleet host facts backfill: no machine missing Fleet facts that is due a check"); + return; + } + Map hostIds = fleetHostIds(tenantId, due); + // Nothing to read yet: the tool connection consumer fills the machine once Fleet confirms its host + List withoutHost = due.stream() + .filter(machine -> !hostIds.containsKey(machine.getMachineId())) + .toList(); + withoutHost.forEach(machine -> machineRepository.markHostFactsChecked(machine.getMachineId(), now)); + int read = hostIds.isEmpty() ? 0 : readHosts(due, hostIds, now); + log.info("Fleet host facts backfill: {} machines due, {} without a confirmed Fleet host, {} Fleet hosts read", + due.size(), withoutHost.size(), read); + } + + private int readHosts(List due, Map hostIds, Instant now) { + FleetMdmClient client = fleetMdmClients.client(); + int read = 0; + for (Machine machine : due) { + Long hostId = hostIds.get(machine.getMachineId()); + if (hostId == null) { + continue; + } + HostRead outcome = fill(client, machine, hostId); + if (outcome == HostRead.FOUND) { + read++; + } + // A read that threw is a transient failure, not an answer: the machine stays due, so a Fleet outage + // does not push it back by recheck-after + if (outcome != HostRead.FAILED) { + machineRepository.markHostFactsChecked(machine.getMachineId(), now); + } + } + return read; + } + + private Map fleetHostIds(String tenantId, List machines) { + List machineIds = machines.stream().map(Machine::getMachineId).toList(); + List connections = toolConnectionRepository.findByTenantIdAndMachineIdInAndToolTypeAndStatus( + tenantId, machineIds, ToolType.FLEET_MDM, ConnectionStatus.CONNECTED); + Map hostIds = new HashMap<>(); + for (ToolConnection connection : connections) { + Long hostId = fleetHostId(connection); + if (hostId != null) { + hostIds.putIfAbsent(connection.getMachineId(), hostId); + } + } + return hostIds; + } + + // A numeric agentToolId is the Fleet host id the transformer confirmed; a UUID there means Fleet never + // confirmed the host, so there is nothing to read yet. A digit string too long for a host id is skipped the same + // way. + private static Long fleetHostId(ToolConnection connection) { + String agentToolId = connection.getAgentToolId(); + if (!isNumeric(agentToolId)) { + return null; + } + try { + return Long.parseLong(agentToolId); + } catch (NumberFormatException e) { + log.warn("Fleet host id out of range, skipped: connectionId={}, agentToolId={}", connection.getId(), agentToolId); + return null; + } + } + + private HostRead fill(FleetMdmClient client, Machine machine, long hostId) { + try { + Host host = client.getHostById(hostId); + if (host == null) { + log.debug("Fleet host {} of machine {} no longer exists", hostId, machine.getMachineId()); + return HostRead.GONE; + } + fleetHostFactsWriter.fill(machine, host); + return HostRead.FOUND; + } catch (Exception e) { + log.warn("Fleet host facts backfill failed: machineId={}, host_id={}", machine.getMachineId(), hostId, e); + return HostRead.FAILED; + } + } + + private enum HostRead { + FOUND, GONE, FAILED + } +} diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsWriter.java b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsWriter.java new file mode 100644 index 0000000000..5aa6700e7c --- /dev/null +++ b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsWriter.java @@ -0,0 +1,73 @@ +package com.openframe.client.service.agentregistration.fleet; + +import com.openframe.data.document.device.Machine; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineField; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriter; +import com.openframe.sdk.fleetmdm.model.Host; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.stereotype.Component; + +import java.util.Set; + +import static com.openframe.data.service.machine.MachineFields.COMPUTER_NAME; +import static com.openframe.data.service.machine.MachineFields.MANUFACTURER; +import static com.openframe.data.service.machine.MachineFields.MODEL; +import static com.openframe.data.service.machine.MachineFields.OS_UUID; +import static com.openframe.data.service.machine.MachineFields.SERIAL_NUMBER; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; +import static org.apache.commons.lang3.StringUtils.isBlank; + +// Fills the machine's hardware facts from its Fleet host where the machine has none. A value the agent reported at +// registration always wins: Fleet never overwrites one. +@Component +@RequiredArgsConstructor +@Slf4j +public class FleetHostFactsWriter { + + private final MachineRepository machineRepository; + private final MachineWriter machineWriter; + + public void fill(String machineId, Host host) { + machineRepository.findByMachineId(machineId).ifPresentOrElse( + machine -> fill(machine, host), + () -> log.warn("Machine not found, Fleet host facts not filled: machineId={}", machineId)); + } + + public void fill(Machine machine, Host host) { + MachineUpdate update = machineUpdate(); + setWhereBlank(update, SERIAL_NUMBER, machine.getSerialNumber(), host.getHardwareSerial()); + setWhereBlank(update, MODEL, machine.getModel(), host.getHardwareModel()); + setWhereBlank(update, MANUFACTURER, machine.getManufacturer(), host.getHardwareVendor()); + setWhereBlank(update, OS_UUID, machine.getOsUuid(), host.getUuid()); + setWhereBlank(update, COMPUTER_NAME, machine.getComputerName(), host.getComputerName()); + String machineId = machine.getMachineId(); + if (update.isEmpty()) { + log.debug("No blank hardware fact Fleet can fill: machineId={}", machineId); + return; + } + log.info("Filling hardware facts from Fleet: machineId={}, fields={}", machineId, update.paths()); + machineWriter.update(machineId, stillBlank(update.paths()), update); + } + + // A value the agent reports between the read and the write wins: the write only lands while every field it + // sets is still blank + private static Criteria stillBlank(Set paths) { + Criteria[] blankFields = paths.stream() + .map(path -> new Criteria().orOperator( + Criteria.where(path).exists(false), + Criteria.where(path).is(null), + Criteria.where(path).is(""))) + .toArray(Criteria[]::new); + return new Criteria().andOperator(blankFields); + } + + private static void setWhereBlank(MachineUpdate update, MachineField field, String stored, String fleetValue) { + if (isBlank(stored) && !isBlank(fleetValue)) { + update.set(field, fleetValue.trim()); + } + } +} diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetMdmClients.java b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetMdmClients.java new file mode 100644 index 0000000000..e9ebaf8db9 --- /dev/null +++ b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/fleet/FleetMdmClients.java @@ -0,0 +1,44 @@ +package com.openframe.client.service.agentregistration.fleet; + +import com.openframe.data.document.tool.IntegratedTool; +import com.openframe.data.document.tool.IntegratedToolId; +import com.openframe.data.service.IntegratedToolService; +import com.openframe.sdk.fleetmdm.FleetMdmClient; +import com.openframe.sdk.fleetmdm.FleetTenantHeader; +import jakarta.annotation.PostConstruct; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.stereotype.Component; + +// Turns the integrated Fleet tool into a client in one place: the agent-id transformer and the host facts backfill +// talk to the same Fleet with the same tenant header. +@Component +@RequiredArgsConstructor +public class FleetMdmClients { + + private final IntegratedToolService integratedToolService; + + @Value("${TENANT_ID:}") + private String tenantId; + + @Value("${openframe.fleet.multi-tenancy.enabled:false}") + private boolean fleetMultiTenancyEnabled; + + @PostConstruct + void validateTenantConfig() { + FleetTenantHeader.validate(fleetMultiTenancyEnabled, tenantId); + } + + public FleetMdmClient client() { + String toolId = IntegratedToolId.FLEET_SERVER_ID.getValue(); + IntegratedTool tool = integratedToolService.getToolByKey(toolId) + .orElseThrow(() -> new IllegalStateException("Found no tool with id " + toolId)); + String apiUrl = tool.apiUrl(); + String apiToken = tool.apiToken(); + return createClient(apiUrl, apiToken); + } + + protected FleetMdmClient createClient(String apiUrl, String apiToken) { + return new FleetMdmClient(apiUrl, apiToken, tenantId); + } +} diff --git a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformer.java b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformer.java index 65f5b092ef..9eccd1453d 100644 --- a/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformer.java +++ b/openframe-client-core/src/main/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformer.java @@ -1,18 +1,12 @@ package com.openframe.client.service.agentregistration.transformer; -import com.openframe.data.document.tool.IntegratedTool; +import com.openframe.client.service.agentregistration.fleet.FleetHostFactsWriter; +import com.openframe.client.service.agentregistration.fleet.FleetMdmClients; import com.openframe.data.document.tool.ToolType; -import com.openframe.data.document.tool.ToolUrl; -import com.openframe.data.document.tool.ToolUrlType; -import com.openframe.data.service.IntegratedToolService; -import com.openframe.data.service.ToolUrlService; import com.openframe.sdk.fleetmdm.FleetMdmClient; -import com.openframe.sdk.fleetmdm.FleetTenantHeader; import com.openframe.sdk.fleetmdm.model.Host; -import jakarta.annotation.PostConstruct; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import java.util.Comparator; @@ -27,21 +21,8 @@ @Slf4j public class FleetMdmAgentIdTransformer implements ToolAgentIdTransformer { - private static final String TOOL_ID = "fleetmdm-server"; - - private final IntegratedToolService integratedToolService; - private final ToolUrlService toolUrlService; - - @Value("${TENANT_ID:}") - private String tenantId; - - @Value("${openframe.fleet.multi-tenancy.enabled:false}") - private boolean fleetMultiTenancyEnabled; - - @PostConstruct - void validateTenantConfig() { - FleetTenantHeader.validate(fleetMultiTenancyEnabled, tenantId); - } + private final FleetMdmClients fleetMdmClients; + private final FleetHostFactsWriter fleetHostFactsWriter; @Override public ToolType getToolType() { @@ -59,16 +40,7 @@ public String transform(String machineId, String agentToolId, boolean lastAttemp } try { - IntegratedTool integratedTool = integratedToolService.getToolByKey(TOOL_ID) - .orElseThrow(() -> new IllegalStateException("Found no tool with id " + TOOL_ID)); - - ToolUrl toolUrl = toolUrlService.getUrlByToolType(integratedTool, ToolUrlType.API) - .orElseThrow(() -> new IllegalStateException("Found no api url for tool with id " + TOOL_ID)); - - String apiUrl = toolUrl.getUrl() + ":" + toolUrl.getPort(); - String apiToken = integratedTool.getCredentials().getApiKey().getKey(); - - FleetMdmClient fleetClient = new FleetMdmClient(apiUrl, apiToken, tenantId); + FleetMdmClient fleetClient = fleetMdmClients.client(); List hosts = fleetClient.searchHosts(agentToolId, 0, 2); @@ -99,9 +71,19 @@ public String transform(String machineId, String agentToolId, boolean lastAttemp private String processMatchingHost(String machineId, String agentToolId, Host host) { String transformedAgentToolId = String.valueOf(host.getId()); log.info("Transformed Fleet MDM agent tool ID, machineId={}, uuid={}, host_id={}", machineId, agentToolId, transformedAgentToolId); + fillHostFacts(machineId, host); return transformedAgentToolId; } + // The facts come for free with the lookup; failing to store them must never fail the tool connection + private void fillHostFacts(String machineId, Host host) { + try { + fleetHostFactsWriter.fill(machineId, host); + } catch (Exception e) { + log.warn("Failed to fill Fleet host facts, machineId={}, host_id={}", machineId, host.getId(), e); + } + } + private String processNoMatchingHost(String machineId, String agentToolId, boolean lastAttempt) { log.warn("No matching host found, machineId={}, uuid={}", machineId, agentToolId); if (!lastAttempt) { diff --git a/openframe-client-core/src/test/java/com/openframe/client/aspect/MachineTagEventServiceImplTest.java b/openframe-client-core/src/test/java/com/openframe/client/aspect/MachineTagEventServiceImplTest.java new file mode 100644 index 0000000000..cb85ae9fb8 --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/aspect/MachineTagEventServiceImplTest.java @@ -0,0 +1,97 @@ +package com.openframe.client.aspect; + +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; +import com.openframe.data.document.device.Machine; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.repository.tag.TagAssignmentRepository; +import com.openframe.data.repository.tag.TagRepository; +import com.openframe.data.service.TenantIdProvider; +import com.openframe.data.service.impl.MachineTagEventServiceImpl; +import com.openframe.kafka.model.KafkaMessage; +import com.openframe.kafka.model.MachinePinotMessage; +import com.openframe.kafka.producer.retry.OssTenantRetryingKafkaProducer; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class MachineTagEventServiceImplTest { + + private static final String TOPIC = "devices-topic"; + private static final String MACHINE_ID = "m-1"; + + @Mock + private MachineRepository machineRepository; + + @Mock + private TagAssignmentRepository tagAssignmentRepository; + + @Mock + private TagRepository tagRepository; + + @Mock + private OssTenantRetryingKafkaProducer kafkaProducer; + + @Mock + private TenantIdProvider tenantIdProvider; + + @Captor + private ArgumentCaptor messageCaptor; + + @InjectMocks + private MachineTagEventServiceImpl service; + + @Test + void processMachineSave_directorySummary_publishedByName() { + // setup + ReflectionTestUtils.setField(service, "machineEventsTopic", TOPIC); + Machine machine = machine(); + machine.setDirectorySources(List.of(DirectorySource.MICROSOFT_365)); + machine.setDirectoryUserLink(DirectoryUserLink.SHARED); + + // execution + service.processMachineSave(machine); + + // verifications + verify(kafkaProducer).publish(eq(TOPIC), eq(MACHINE_ID), messageCaptor.capture()); + MachinePinotMessage message = (MachinePinotMessage) messageCaptor.getValue(); + assertThat(message) + .extracting(MachinePinotMessage::getDirectorySources, MachinePinotMessage::getDirectoryUserLink) + .containsExactly(List.of("MICROSOFT_365"), "SHARED"); + } + + @Test + void processMachineSave_machineNeverWrittenByTheMatcher_noSourcesAndNone() { + // setup + ReflectionTestUtils.setField(service, "machineEventsTopic", TOPIC); + Machine machine = machine(); + + // execution + service.processMachineSave(machine); + + // verifications + verify(kafkaProducer).publish(eq(TOPIC), eq(MACHINE_ID), messageCaptor.capture()); + MachinePinotMessage message = (MachinePinotMessage) messageCaptor.getValue(); + assertThat(message) + .extracting(MachinePinotMessage::getDirectorySources, MachinePinotMessage::getDirectoryUserLink) + .containsExactly(List.of(), "NONE"); + } + + private static Machine machine() { + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + return machine; + } +} diff --git a/openframe-client-core/src/test/java/com/openframe/client/integration/MachineFieldLevelWritesIT.java b/openframe-client-core/src/test/java/com/openframe/client/integration/MachineFieldLevelWritesIT.java new file mode 100644 index 0000000000..0ffb089e68 --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/integration/MachineFieldLevelWritesIT.java @@ -0,0 +1,260 @@ +package com.openframe.client.integration; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.openframe.client.dto.agent.AgentRegistrationRequest; +import com.openframe.client.service.AgentUninstallService; +import com.openframe.client.service.InstalledAgentService; +import com.openframe.client.service.MachineHostnameService; +import com.openframe.client.service.MachineStatusService; +import com.openframe.client.service.MachineTimezoneService; +import com.openframe.client.service.ToolConnectionService; +import com.openframe.client.service.agentregistration.AgentRegistrationClientFeatureFlagsService; +import com.openframe.client.service.agentregistration.AgentRegistrationClientUpdateService; +import com.openframe.client.service.agentregistration.AgentRegistrationService; +import com.openframe.client.service.agentregistration.AgentRegistrationToolInstallationService; +import com.openframe.client.service.agentregistration.AgentSecretGenerator; +import com.openframe.client.service.agentregistration.MachineIdGenerator; +import com.openframe.client.service.agentregistration.OrganizationIdResolver; +import com.openframe.client.service.agentregistration.RegistrationTagAssignmentService; +import com.openframe.client.service.agentregistration.processor.AgentRegistrationProcessor; +import com.openframe.client.service.validator.AgentRegistrationSecretValidator; +import com.openframe.client.service.validator.ClientSecretValidator; +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; +import com.openframe.data.document.device.Machine; +import com.openframe.data.document.device.TelemetryStatus; +import com.openframe.data.document.oauth.OAuthClient; +import com.openframe.data.repository.device.CustomMachineRepositoryImpl; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.repository.oauth.OAuthClientRepository; +import com.openframe.data.service.machine.MachineWriter; +import com.openframe.data.service.rmm.DeletedMachineCleanup; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.Arguments; +import org.junit.jupiter.params.provider.MethodSource; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory; +import org.springframework.data.repository.core.support.RepositoryComposition.RepositoryFragments; +import org.springframework.security.crypto.password.PasswordEncoder; +import org.testcontainers.mongodb.MongoDBContainer; +import org.testcontainers.utility.DockerImageName; + +import java.time.Instant; +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Stream; + +import static com.openframe.data.service.machine.MachineFields.COMPUTER_NAME; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_SOURCES; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_IDS; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_LINK; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_NAME; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.AdditionalAnswers.delegatesTo; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +// The post-registration writers read the machine, decide, then write. Between the read and the write an external +// directory integration (or the Fleet facts writer) may $set its own fields: each path must write only the fields it +// owns, so those concurrent values survive. +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class MachineFieldLevelWritesIT { + + private static final String MACHINE_ID = "m-1"; + private static final String SECRET = "secret"; + private static final Instant SEEN = Instant.parse("2026-01-01T00:00:00Z"); + private static final Instant LATER = Instant.parse("2026-01-01T00:05:00Z"); + + private static final MongoDBContainer MONGO = new MongoDBContainer(DockerImageName.parse("mongo:7")); + + private static MongoClient client; + private static MongoTemplate template; + private static MachineRepository storedMachines; + private static MachineWriter machineWriter; + + private Services services; + + @BeforeAll + static void startMongo() { + String uri = System.getProperty("mongo.external.uri"); + if (uri == null) { + if (!MONGO.isRunning()) { + MONGO.start(); + } + uri = MONGO.getConnectionString() + "/?directConnection=true"; + } + client = MongoClients.create(uri); + template = new MongoTemplate(client, "test"); + storedMachines = new MongoRepositoryFactory(template).getRepository(MachineRepository.class, + RepositoryFragments.just(new CustomMachineRepositoryImpl(template))); + machineWriter = new MachineWriter(template, absent(), absent()); + } + + // Publishing off: no OutboxPublisher bean. + @SuppressWarnings("unchecked") + private static ObjectProvider absent() { + return mock(ObjectProvider.class); + } + + @AfterAll + static void stopMongo() { + client.close(); + } + + @BeforeEach + void setUp() { + template.dropCollection(Machine.class); + services = new Services(interleavingRepository()); + } + + static Stream postRegistrationWriters() { + return Stream.of( + path("status transition PENDING -> ONLINE", DeviceStatus.PENDING, + s -> s.status().updateToOnline(MACHINE_ID, LATER), + m -> m.getStatus() == DeviceStatus.ONLINE && LATER.equals(m.getFirstConnectedAt())), + path("connectivity flip of a deleted machine", DeviceStatus.DELETED, + s -> s.status().updateToOffline(MACHINE_ID, LATER), + m -> m.getTelemetryStatus() == TelemetryStatus.OFFLINE && m.getStatus() == DeviceStatus.DELETED), + path("timezone update", DeviceStatus.ONLINE, + s -> s.timezone().updateTimezone(MACHINE_ID, "Europe/Kyiv"), + m -> "Europe/Kyiv".equals(m.getTimezone())), + path("hostname update", DeviceStatus.ONLINE, + s -> s.hostname().updateHostname(MACHINE_ID, "new-host"), + m -> "new-host".equals(m.getHostname())), + path("agent uninstall", DeviceStatus.ONLINE, + s -> s.uninstall().uninstall(MACHINE_ID, SECRET), + m -> m.getStatus() == DeviceStatus.DELETED), + path("re-registration of an existing machine", DeviceStatus.ONLINE, + s -> s.registration().reinstall("initial-key", MACHINE_ID, SECRET, reinstallRequest()), + m -> m.getStatus() == DeviceStatus.PENDING && "reinstalled-host".equals(m.getHostname()) + && "org-2".equals(m.getOrganizationId())) + ); + } + + @ParameterizedTest(name = "{0}") + @MethodSource("postRegistrationWriters") + void write_concurrentDirectoryAndFleetSetBetweenReadAndWrite_survives(String path, DeviceStatus seededStatus, + Consumer action, + Function ownChangeLanded) { + // setup + seed(seededStatus); + + // execution + action.accept(services); + + // verifications + Machine stored = storedMachines.findByMachineId(MACHINE_ID).orElseThrow(); + assertThat(ownChangeLanded.apply(stored)).as("the path's own change").isTrue(); + assertThat(stored).extracting(Machine::getDirectorySources, Machine::getDirectoryUserLink, + Machine::getDirectoryUserIds, Machine::getDirectoryUserName, Machine::getComputerName) + .containsExactly(List.of(DirectorySource.MICROSOFT_365), DirectoryUserLink.PRIMARY, + List.of("acc-1"), "Jane Doe", "Jane's MacBook Pro"); + } + + private static Arguments path(String name, DeviceStatus seededStatus, Consumer action, + Function ownChangeLanded) { + return Arguments.of(name, seededStatus, action, ownChangeLanded); + } + + // Every read of the machine is followed by the concurrent write, before the service gets to write + private static MachineRepository interleavingRepository() { + MachineRepository repository = mock(MachineRepository.class, delegatesTo(storedMachines)); + doAnswer(invocation -> { + Optional read = storedMachines.findByMachineId(invocation.getArgument(0)); + concurrentDirectoryAndFleetWrite(); + return read; + }).when(repository).findByMachineId(anyString()); + return repository; + } + + private static void concurrentDirectoryAndFleetWrite() { + machineWriter.update(MACHINE_ID, machineUpdate() + .set(DIRECTORY_SOURCES, List.of(DirectorySource.MICROSOFT_365)) + .set(DIRECTORY_USER_LINK, DirectoryUserLink.PRIMARY) + .set(DIRECTORY_USER_IDS, List.of("acc-1")) + .set(DIRECTORY_USER_NAME, "Jane Doe") + .set(COMPUTER_NAME, "Jane's MacBook Pro")); + } + + private static void seed(DeviceStatus status) { + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + machine.setTenantId("tenant-1"); + machine.setStatus(status); + machine.setTelemetryStatus(TelemetryStatus.ONLINE); + machine.setLastSeen(SEEN); + machine.setHostname("old-host"); + machine.setTimezone("UTC"); + machine.setOrganizationId("org-1"); + template.save(machine); + } + + private static AgentRegistrationRequest reinstallRequest() { + AgentRegistrationRequest request = new AgentRegistrationRequest(); + request.setHostname("reinstalled-host"); + request.setOrganizationId("org-2"); + request.setOsType("WINDOWS"); + request.setAgentVersion("1.0.0"); + return request; + } + + record Services(MachineStatusService status, MachineTimezoneService timezone, MachineHostnameService hostname, + AgentUninstallService uninstall, AgentRegistrationService registration) { + + Services(MachineRepository machines) { + this(new MachineStatusService(machines, machineWriter, mock(ApplicationEventPublisher.class)), + new MachineTimezoneService(machines, machineWriter), + new MachineHostnameService(machines, machineWriter), + uninstallService(machines), + registrationService(machines)); + } + + private static AgentUninstallService uninstallService(MachineRepository machines) { + return new AgentUninstallService(knownClient(false), mock(ClientSecretValidator.class), machines, machineWriter, + mock(ToolConnectionService.class), mock(InstalledAgentService.class), + mock(DeletedMachineCleanup.class), mock(ApplicationEventPublisher.class)); + } + + private static AgentRegistrationService registrationService(MachineRepository machines) { + OrganizationIdResolver organizations = mock(OrganizationIdResolver.class); + when(organizations.resolve("org-2")).thenReturn("org-2"); + // a reinstall no longer reads the machine, so the concurrent write lands after its first read, the client + return new AgentRegistrationService(knownClient(true), machines, machineWriter, organizations, + mock(AgentRegistrationSecretValidator.class), mock(ClientSecretValidator.class), + mock(AgentSecretGenerator.class), mock(PasswordEncoder.class), mock(MachineIdGenerator.class), + mock(AgentRegistrationToolInstallationService.class), mock(AgentRegistrationProcessor.class), + mock(RegistrationTagAssignmentService.class), mock(InstalledAgentService.class), + mock(ToolConnectionService.class), mock(AgentRegistrationClientFeatureFlagsService.class), + mock(AgentRegistrationClientUpdateService.class)); + } + + private static OAuthClientRepository knownClient(boolean concurrentWriteAfterTheRead) { + OAuthClient oauthClient = new OAuthClient(); + oauthClient.setMachineId(MACHINE_ID); + oauthClient.setClientId("agent_" + MACHINE_ID); + OAuthClientRepository clients = mock(OAuthClientRepository.class); + when(clients.findByMachineId(MACHINE_ID)).thenAnswer(invocation -> { + if (concurrentWriteAfterTheRead) { + concurrentDirectoryAndFleetWrite(); + } + return Optional.of(oauthClient); + }); + return clients; + } + } +} diff --git a/openframe-client-core/src/test/java/com/openframe/client/metrics/DeviceOnlineDispatchMetricsTest.java b/openframe-client-core/src/test/java/com/openframe/client/metrics/DeviceOnlineDispatchMetricsTest.java index 7fa51ee269..381735bc6e 100644 --- a/openframe-client-core/src/test/java/com/openframe/client/metrics/DeviceOnlineDispatchMetricsTest.java +++ b/openframe-client-core/src/test/java/com/openframe/client/metrics/DeviceOnlineDispatchMetricsTest.java @@ -17,11 +17,12 @@ class DeviceOnlineDispatchMetricsTest { private final DeviceOnlineDispatchRepository repository = mock(DeviceOnlineDispatchRepository.class); private final SimpleMeterRegistry registry = new SimpleMeterRegistry(); + // Micrometer gauges hold their object weakly: without this reference a GC turns them into NaN. + private final DeviceOnlineDispatchMetrics metrics = + new DeviceOnlineDispatchMetrics(repository, registry, BATCH_SIZE); @Test void gaugeReportsNewSentinelCountAfterRefresh() { - DeviceOnlineDispatchMetrics metrics = new DeviceOnlineDispatchMetrics(repository, registry, BATCH_SIZE); - // Before the first refresh the gauge sits at its initial value. assertThat(registry.get(PENDING_GAUGE).gauge().value()).isEqualTo(0.0); @@ -33,16 +34,12 @@ void gaugeReportsNewSentinelCountAfterRefresh() { @Test void batchSizeGaugePublishesConfiguredThreshold() { - new DeviceOnlineDispatchMetrics(repository, registry, BATCH_SIZE); - // The alert compares pending > batch_size, so the configured batch-size is published as a gauge. assertThat(registry.get(BATCH_SIZE_GAUGE).gauge().value()).isEqualTo(500.0); } @Test void refreshSwallowsRepositoryErrorsAndKeepsLastValue() { - DeviceOnlineDispatchMetrics metrics = new DeviceOnlineDispatchMetrics(repository, registry, BATCH_SIZE); - when(repository.countByStatus(DeviceOnlineDispatchStatus.NEW)).thenReturn(10L); metrics.refreshPending(); diff --git a/openframe-client-core/src/test/java/com/openframe/client/scheduler/FleetHostFactsBackfillSchedulerTest.java b/openframe-client-core/src/test/java/com/openframe/client/scheduler/FleetHostFactsBackfillSchedulerTest.java new file mode 100644 index 0000000000..474815fb98 --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/scheduler/FleetHostFactsBackfillSchedulerTest.java @@ -0,0 +1,46 @@ +package com.openframe.client.scheduler; + +import com.openframe.client.service.agentregistration.fleet.FleetHostFactsBackfillService; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class FleetHostFactsBackfillSchedulerTest { + + @Mock + private FleetHostFactsBackfillService backfillService; + + @InjectMocks + private FleetHostFactsBackfillScheduler scheduler; + + @Test + void run_scheduledTick_delegatesToTheBackfill() { + // setup + + // execution + scheduler.run(); + + // verifications + verify(backfillService).backfill(); + } + + @Test + void run_backfillFails_failureLoggedNotThrown() { + // setup + doThrow(new IllegalStateException("Found no tool with id fleetmdm-server")).when(backfillService).backfill(); + + // execution + Throwable thrown = catchThrowable(scheduler::run); + + // verifications + assertThat(thrown).isNull(); + } +} diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/AgentRegistrationServiceTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/AgentRegistrationServiceTest.java index 4c07d43b8b..bda1ad01a9 100644 --- a/openframe-client-core/src/test/java/com/openframe/client/service/AgentRegistrationServiceTest.java +++ b/openframe-client-core/src/test/java/com/openframe/client/service/AgentRegistrationServiceTest.java @@ -16,6 +16,9 @@ import com.openframe.data.document.rmm.script.OsType; import com.openframe.data.repository.device.MachineRepository; import com.openframe.data.repository.oauth.OAuthClientRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriteResult; +import com.openframe.data.service.machine.MachineWriter; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -24,6 +27,7 @@ import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.BeanUtils; import org.springframework.security.crypto.password.PasswordEncoder; import java.util.List; @@ -44,6 +48,9 @@ class AgentRegistrationServiceTest { @Mock private MachineRepository machineRepository; + @Mock + private MachineWriter machineWriter; + @Mock private RegistrationTagAssignmentService registrationTagAssignmentService; @@ -101,6 +108,7 @@ void setUp() { agentRegistrationService = new AgentRegistrationService( oauthClientRepository, machineRepository, + machineWriter, organizationIdResolver, agentRegistrationSecretValidator, clientSecretValidator, @@ -178,6 +186,7 @@ void registerAgent_WithExistingMachine_ThrowsException() { verify(oauthClientRepository).existsByMachineId(MACHINE_ID); verify(oauthClientRepository, never()).save(any()); verify(machineRepository, never()).save(any()); + verifyNoInteractions(machineWriter); } @Test @@ -231,7 +240,7 @@ void reinstall_WithValidKeyAndSecret_OverwritesMachineAndReturnsExistingCreds() existingMachine.setAgentVersion("0.9.0"); existingMachine.setOrganizationId("old-org"); when(oauthClientRepository.findByMachineId(MACHINE_ID)).thenReturn(Optional.of(existingClient)); - when(machineRepository.findByMachineId(MACHINE_ID)).thenReturn(Optional.of(existingMachine)); + stubWriterOver(existingMachine); when(organizationIdResolver.resolve("org-1")).thenReturn("new-org"); AgentRegistrationResponse response = @@ -247,9 +256,9 @@ void reinstall_WithValidKeyAndSecret_OverwritesMachineAndReturnsExistingCreds() inOrder.verify(agentRegistrationSecretValidator).validate(INITIAL_KEY); inOrder.verify(clientSecretValidator).validate(existingClient, CLIENT_SECRET); - // existing machine row is overwritten with request data (same id), not recreated - verify(machineRepository).save(machineCaptor.capture()); - Machine savedMachine = machineCaptor.getValue(); + // existing machine row is overwritten with request data (same id), field by field, not recreated or saved whole + verify(machineRepository, never()).save(any()); + Machine savedMachine = writtenOver(existingMachine); assertEquals(MACHINE_ID, savedMachine.getMachineId()); assertEquals("test-hostname", savedMachine.getHostname()); assertEquals(OsType.WINDOWS, savedMachine.getOsType()); @@ -267,7 +276,8 @@ void reinstall_WithValidKeyAndSecret_OverwritesMachineAndReturnsExistingCreds() // setup is re-run verify(registrationTagAssignmentService).assignTags(eq(MACHINE_ID), any()); verify(agentRegistrationToolInstallationService).process(MACHINE_ID); - verify(agentRegistrationProcessor).postProcessAgentRegistration(existingMachine, request); + verify(agentRegistrationProcessor).postProcessAgentRegistration(machineCaptor.capture(), eq(request)); + assertEquals("new-org", machineCaptor.getValue().getOrganizationId()); verify(installedAgentService).addInstalledAgent(MACHINE_ID, "openframe-client", "1.0.0", false); // nothing is re-created @@ -290,6 +300,7 @@ void reinstall_WithInvalidInitialKey_FailsBeforeClientSecretCheck() { verify(clientSecretValidator, never()).validate(any(), any()); verify(machineRepository, never()).findByMachineId(any()); verify(machineRepository, never()).save(any()); + verifyNoInteractions(machineWriter); verify(oauthClientRepository, never()).save(any()); } @@ -308,6 +319,7 @@ void reinstall_WithUnknownMachine_ThrowsGenericInvalidSecret() { verify(clientSecretValidator, never()).validate(any(), any()); verify(machineRepository, never()).findByMachineId(any()); verify(machineRepository, never()).save(any()); + verifyNoInteractions(machineWriter); } @Test @@ -326,6 +338,7 @@ void reinstall_WithInvalidClientSecret_ThrowsAndDoesNotTouchMachine() { verify(agentRegistrationSecretValidator).validate(INITIAL_KEY); verify(machineRepository, never()).findByMachineId(any()); verify(machineRepository, never()).save(any()); + verifyNoInteractions(machineWriter); verify(oauthClientRepository, never()).save(any()); } @@ -340,4 +353,147 @@ private AgentRegistrationRequest createTestRequest() { request.setAgentVersion("1.0.0"); return request; } + + @Test + void registerAgent_WithHardwareFacts_CopiesThemOntoTheNewMachine() { + stubNewMachineRegistration(); + request.setSerialNumber("C02XG2JHJG5H"); + request.setManufacturer("Apple Inc."); + request.setModel("MacBookPro18,3"); + + agentRegistrationService.register(INITIAL_KEY, request); + + verify(machineRepository).save(machineCaptor.capture()); + Machine savedMachine = machineCaptor.getValue(); + assertEquals("C02XG2JHJG5H", savedMachine.getSerialNumber()); + assertEquals("Apple Inc.", savedMachine.getManufacturer()); + assertEquals("MacBookPro18,3", savedMachine.getModel()); + assertEquals("test-os-uuid", savedMachine.getOsUuid()); + } + + @Test + void registerAgent_WithBlankHardwareFacts_LeavesThemUnset() { + stubNewMachineRegistration(); + request.setSerialNumber(" "); + request.setManufacturer(""); + request.setModel(null); + request.setOsUuid(" "); + + agentRegistrationService.register(INITIAL_KEY, request); + + verify(machineRepository).save(machineCaptor.capture()); + Machine savedMachine = machineCaptor.getValue(); + assertNull(savedMachine.getSerialNumber()); + assertNull(savedMachine.getManufacturer()); + assertNull(savedMachine.getModel()); + assertNull(savedMachine.getOsUuid()); + } + + @Test + void reinstall_WithHardwareFacts_OverwritesTheStoredOnes() { + stubReinstallOf(machineWithHardwareFacts()); + request.setSerialNumber("NEW-SERIAL"); + request.setManufacturer("Dell Inc."); + request.setModel("Latitude 7440"); + request.setOsUuid("new-os-uuid"); + + agentRegistrationService.reinstall(INITIAL_KEY, MACHINE_ID, CLIENT_SECRET, request); + + Machine savedMachine = writtenOver(machineWithHardwareFacts()); + assertEquals("NEW-SERIAL", savedMachine.getSerialNumber()); + assertEquals("Dell Inc.", savedMachine.getManufacturer()); + assertEquals("Latitude 7440", savedMachine.getModel()); + assertEquals("new-os-uuid", savedMachine.getOsUuid()); + } + + @Test + void reinstall_WithoutHardwareFacts_KeepsTheStoredOnes() { + stubReinstallOf(machineWithHardwareFacts()); + request.setSerialNumber(" "); + request.setOsUuid(null); + + agentRegistrationService.reinstall(INITIAL_KEY, MACHINE_ID, CLIENT_SECRET, request); + + Machine savedMachine = writtenOver(machineWithHardwareFacts()); + assertEquals("OLD-SERIAL", savedMachine.getSerialNumber()); + assertEquals("LENOVO", savedMachine.getManufacturer()); + assertEquals("ThinkPad T14", savedMachine.getModel()); + assertEquals("old-os-uuid", savedMachine.getOsUuid()); + } + + @Test + void reinstall_WithUserId_RecordsWhoInstalledTheAgent() { + stubReinstallOf(machineWithHardwareFacts()); + request.setUserId("new-user"); + + agentRegistrationService.reinstall(INITIAL_KEY, MACHINE_ID, CLIENT_SECRET, request); + + Machine savedMachine = writtenOver(machineWithHardwareFacts()); + assertEquals("new-user", savedMachine.getUserId()); + } + + @Test + void reinstall_WithoutUserId_KeepsTheStoredOne() { + stubReinstallOf(machineWithHardwareFacts()); + request.setUserId(" "); + + agentRegistrationService.reinstall(INITIAL_KEY, MACHINE_ID, CLIENT_SECRET, request); + + Machine savedMachine = writtenOver(machineWithHardwareFacts()); + assertEquals("old-user", savedMachine.getUserId()); + } + + private void stubNewMachineRegistration() { + when(machineIdGenerator.generate()).thenReturn(MACHINE_ID); + when(oauthClientRepository.existsByMachineId(MACHINE_ID)).thenReturn(false); + when(agentSecretGenerator.generate()).thenReturn(CLIENT_SECRET); + when(organizationIdResolver.resolve(any())).thenReturn(ORGANIZATION_ID); + when(passwordEncoder.encode(CLIENT_SECRET)).thenReturn("encoded-secret"); + when(oauthClientRepository.save(any())).thenAnswer(i -> i.getArguments()[0]); + when(machineRepository.save(any())).thenAnswer(i -> i.getArguments()[0]); + } + + private void stubReinstallOf(Machine existingMachine) { + OAuthClient existingClient = new OAuthClient(); + existingClient.setMachineId(MACHINE_ID); + existingClient.setClientId("agent_" + MACHINE_ID); + when(oauthClientRepository.findByMachineId(MACHINE_ID)).thenReturn(Optional.of(existingClient)); + stubWriterOver(existingMachine); + when(organizationIdResolver.resolve("org-1")).thenReturn("new-org"); + } + + private void stubWriterOver(Machine existingMachine) { + when(machineWriter.update(eq(MACHINE_ID), any(MachineUpdate.class))).thenAnswer(invocation -> { + Machine after = copyOf(existingMachine); + invocation.getArgument(1, MachineUpdate.class).applyTo(after); + return Optional.of(new MachineWriteResult(existingMachine, after)); + }); + } + + private Machine writtenOver(Machine existingMachine) { + ArgumentCaptor update = ArgumentCaptor.forClass(MachineUpdate.class); + verify(machineWriter).update(eq(MACHINE_ID), update.capture()); + assertFalse(update.getValue().paths().stream().anyMatch(path -> path.startsWith("directory")), + "a reinstall never writes the directory summary"); + Machine after = copyOf(existingMachine); + update.getValue().applyTo(after); + return after; + } + + private static Machine copyOf(Machine source) { + Machine copy = new Machine(); + BeanUtils.copyProperties(source, copy); + return copy; + } + + private static Machine machineWithHardwareFacts() { + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + machine.setSerialNumber("OLD-SERIAL"); + machine.setManufacturer("LENOVO"); + machine.setModel("ThinkPad T14"); + machine.setOsUuid("old-os-uuid"); + machine.setUserId("old-user"); + return machine; + } } diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/AgentUninstallServiceTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/AgentUninstallServiceTest.java index f4e46f6446..fb79cd1168 100644 --- a/openframe-client-core/src/test/java/com/openframe/client/service/AgentUninstallServiceTest.java +++ b/openframe-client-core/src/test/java/com/openframe/client/service/AgentUninstallServiceTest.java @@ -7,6 +7,9 @@ import com.openframe.data.document.oauth.OAuthClient; import com.openframe.data.repository.device.MachineRepository; import com.openframe.data.repository.oauth.OAuthClientRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriteResult; +import com.openframe.data.service.machine.MachineWriter; import com.openframe.data.service.rmm.DeletedMachineCleanup; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; @@ -21,6 +24,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoInteractions; @@ -36,6 +41,7 @@ class AgentUninstallServiceTest { @Mock private OAuthClientRepository oauthClientRepository; @Mock private ClientSecretValidator clientSecretValidator; @Mock private MachineRepository machineRepository; + @Mock private MachineWriter machineWriter; @Mock private ToolConnectionService toolConnectionService; @Mock private InstalledAgentService installedAgentService; @Mock private DeletedMachineCleanup deletedMachineCleanup; @@ -57,11 +63,19 @@ private Machine machineIs(DeviceStatus status) { @DisplayName("uninstall marks the machine DELETED, cleans up schedules and publishes DeviceUninstalledEvent") void uninstallDeletesAndPublishes() { Machine machine = machineIs(DeviceStatus.PENDING_DELETION); + Machine deleted = new Machine(); + deleted.setMachineId(MACHINE); + deleted.setTenantId(TENANT); + deleted.setStatus(DeviceStatus.DELETED); + when(machineWriter.update(eq(MACHINE), any(MachineUpdate.class))) + .thenReturn(Optional.of(new MachineWriteResult(machine, deleted))); service.uninstall(MACHINE, SECRET); - assertThat(machine.getStatus()).isEqualTo(DeviceStatus.DELETED); - verify(machineRepository).save(machine); + ArgumentCaptor update = ArgumentCaptor.forClass(MachineUpdate.class); + verify(machineWriter).update(eq(MACHINE), update.capture()); + assertThat(update.getValue().paths()).containsExactly("status"); + verify(machineRepository, never()).save(any()); verify(deletedMachineCleanup).cleanUpDeletedMachine(TENANT, MACHINE); ArgumentCaptor event = ArgumentCaptor.forClass(DeviceUninstalledEvent.class); verify(eventPublisher).publishEvent(event.capture()); @@ -75,7 +89,7 @@ void alreadyDeletedIsNoOp() { service.uninstall(MACHINE, SECRET); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); verifyNoInteractions(deletedMachineCleanup, eventPublisher); } @@ -89,4 +103,15 @@ void missingMachinePublishesNothing() { verifyNoInteractions(eventPublisher); } + + @Test + @DisplayName("a machine document removed between the read and the write publishes nothing") + void machineGoneBeforeTheWrite_publishesNothing() { + machineIs(DeviceStatus.ONLINE); + when(machineWriter.update(eq(MACHINE), any(MachineUpdate.class))).thenReturn(Optional.empty()); + + service.uninstall(MACHINE, SECRET); + + verifyNoInteractions(deletedMachineCleanup, eventPublisher); + } } diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/MachineStatusServiceTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/MachineStatusServiceTest.java index c93e585074..c6f1dc91ff 100644 --- a/openframe-client-core/src/test/java/com/openframe/client/service/MachineStatusServiceTest.java +++ b/openframe-client-core/src/test/java/com/openframe/client/service/MachineStatusServiceTest.java @@ -7,6 +7,10 @@ import com.openframe.data.document.device.Machine; import com.openframe.data.document.device.TelemetryStatus; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriteResult; +import com.openframe.data.service.machine.MachineWriter; +import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -14,15 +18,23 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.beans.BeanUtils; import org.springframework.context.ApplicationEventPublisher; +import org.springframework.data.mongodb.core.query.Criteria; import java.time.Instant; +import java.util.List; import java.util.Optional; +import java.util.Set; import static org.assertj.core.api.Assertions.assertThat; import static org.assertj.core.api.Assertions.assertThatThrownBy; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.mockingDetails; +import static org.mockito.Mockito.verifyNoInteractions; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -36,10 +48,27 @@ class MachineStatusServiceTest { private static final Instant EARLIER = Instant.parse("2025-12-31T23:55:00Z"); @Mock private MachineRepository machineRepository; + @Mock private MachineWriter machineWriter; @Mock private ApplicationEventPublisher eventPublisher; @InjectMocks private MachineStatusService service; + private Machine stored; + + @BeforeEach + void writerAppliesTheUpdateToTheStoredMachine() { + lenient().when(machineWriter.update(eq(MACHINE), any(MachineUpdate.class))).thenAnswer(invocation -> { + Machine after = copyOf(stored); + invocation.getArgument(1, MachineUpdate.class).applyTo(after); + return Optional.of(new MachineWriteResult(stored, after)); + }); + lenient().when(machineWriter.update(eq(MACHINE), any(Criteria.class), any(MachineUpdate.class))).thenAnswer(invocation -> { + Machine after = copyOf(stored); + invocation.getArgument(2, MachineUpdate.class).applyTo(after); + return Optional.of(new MachineWriteResult(stored, after)); + }); + } + private Machine machine(DeviceStatus status) { return machine(status, SEEN); } @@ -54,7 +83,12 @@ private Machine machine(DeviceStatus status, Instant lastSeen) { } private void machineIs(DeviceStatus status) { - when(machineRepository.findByMachineId(MACHINE)).thenReturn(Optional.of(machine(status))); + storedMachineIs(machine(status)); + } + + private void storedMachineIs(Machine machine) { + stored = machine; + when(machineRepository.findByMachineId(MACHINE)).thenReturn(Optional.of(machine)); } @Test @@ -96,7 +130,7 @@ void onlineHeartbeat_updatesLastSeenOnly() { service.processHeartbeat(MACHINE, LATER); verify(machineRepository).updateLastSeen(MACHINE, LATER); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); } @Test @@ -116,10 +150,9 @@ void offlineToOnline_savesAndPublishes() { service.updateToOnline(MACHINE, LATER); - ArgumentCaptor saved = ArgumentCaptor.forClass(Machine.class); - verify(machineRepository).save(saved.capture()); - assertThat(saved.getValue().getStatus()).isEqualTo(DeviceStatus.ONLINE); - assertThat(saved.getValue().getLastSeen()).isEqualTo(LATER); + Machine written = written(); + assertThat(written.getStatus()).isEqualTo(DeviceStatus.ONLINE); + assertThat(written.getLastSeen()).isEqualTo(LATER); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); verify(eventPublisher).publishEvent(any(DeviceCameOnlineEvent.class)); } @@ -131,7 +164,7 @@ void pendingToOnline_saves() { service.updateToOnline(MACHINE, LATER); - verify(machineRepository).save(any(Machine.class)); + verify(machineWriter).update(eq(MACHINE), any(Criteria.class), any(MachineUpdate.class)); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); verify(eventPublisher).publishEvent(any(DeviceFirstConnectedEvent.class)); } @@ -143,7 +176,7 @@ void pendingToOffline_saves() { service.updateToOffline(MACHINE, LATER); - verify(machineRepository).save(any(Machine.class)); + verify(machineWriter).update(eq(MACHINE), any(Criteria.class), any(MachineUpdate.class)); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); verify(eventPublisher).publishEvent(any(DeviceFirstConnectedEvent.class)); } @@ -155,7 +188,7 @@ void nullStatus_saves() { service.processHeartbeat(MACHINE, LATER); - verify(machineRepository).save(any(Machine.class)); + verify(machineWriter).update(eq(MACHINE), any(Criteria.class), any(MachineUpdate.class)); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); } @@ -166,7 +199,7 @@ void staleEvent_touchesNothing() { service.processHeartbeat(MACHINE, EARLIER); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); } @@ -177,7 +210,7 @@ void eventEqualToLastSeen_touchesNothing() { service.processHeartbeat(MACHINE, SEEN); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); } @@ -189,19 +222,18 @@ void offlineToOffline_updatesLastSeenOnly() { service.updateToOffline(MACHINE, LATER); verify(machineRepository).updateLastSeen(MACHINE, LATER); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); } @Test @DisplayName("T10: an ONLINE device that has never been seen still takes the lastSeen-only path") void nullLastSeen_onlineDevice_updatesLastSeenOnly() { - when(machineRepository.findByMachineId(MACHINE)) - .thenReturn(Optional.of(machine(DeviceStatus.ONLINE, null))); + storedMachineIs(machine(DeviceStatus.ONLINE, null)); service.processHeartbeat(MACHINE, LATER); verify(machineRepository).updateLastSeen(MACHINE, LATER); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); } @Test @@ -212,7 +244,7 @@ void unknownMachine_throwsAndWritesNothing() { assertThatThrownBy(() -> service.processHeartbeat(MACHINE, LATER)) .isInstanceOf(MachineNotFoundException.class); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); } @@ -224,21 +256,20 @@ void pendingDeletion_presenceOnly() { service.processHeartbeat(MACHINE, LATER); verify(machineRepository).updateLastSeen(MACHINE, LATER); - verify(machineRepository, never()).save(any(Machine.class)); + verifyNoInteractions(machineWriter); } @Test @DisplayName("T11b: a deleted device that disconnects records the connectivity flip, status untouched") void deleted_connectivityFlipSaved() { - Machine machine = machine(DeviceStatus.DELETED); - when(machineRepository.findByMachineId(MACHINE)).thenReturn(Optional.of(machine)); + machineIs(DeviceStatus.DELETED); service.updateToOffline(MACHINE, LATER); - verify(machineRepository).save(machine); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); - assertThat(machine.getStatus()).isEqualTo(DeviceStatus.DELETED); - assertThat(machine.getTelemetryStatus()).isEqualTo(TelemetryStatus.OFFLINE); + assertThat(writtenPaths()).containsExactlyInAnyOrder("telemetryStatus", "lastSeen"); + assertThat(written().getStatus()).isEqualTo(DeviceStatus.DELETED); + assertThat(written().getTelemetryStatus()).isEqualTo(TelemetryStatus.OFFLINE); } @Test @@ -246,14 +277,13 @@ void deleted_connectivityFlipSaved() { void firstHeartbeat_telemetryStillEmpty_saved() { Machine machine = machine(DeviceStatus.ONLINE); machine.setTelemetryStatus(null); - when(machineRepository.findByMachineId(MACHINE)).thenReturn(Optional.of(machine)); + storedMachineIs(machine); service.processHeartbeat(MACHINE, LATER); - verify(machineRepository).save(machine); verify(machineRepository, never()).updateLastSeen(anyString(), any(Instant.class)); - assertThat(machine.getTelemetryStatus()).isEqualTo(TelemetryStatus.ONLINE); - assertThat(machine.getStatus()).isEqualTo(DeviceStatus.ONLINE); + assertThat(written().getTelemetryStatus()).isEqualTo(TelemetryStatus.ONLINE); + assertThat(written().getStatus()).isEqualTo(DeviceStatus.ONLINE); } @Test @@ -261,7 +291,7 @@ void firstHeartbeat_telemetryStillEmpty_saved() { void pendingToOnline_stampsFirstConnectedAtWithEventTimestamp() { machineIs(DeviceStatus.PENDING); service.updateToOnline(MACHINE, LATER); - assertThat(savedMachine().getFirstConnectedAt()).isEqualTo(LATER); + assertThat(written().getFirstConnectedAt()).isEqualTo(LATER); } @Test @@ -269,7 +299,7 @@ void pendingToOnline_stampsFirstConnectedAtWithEventTimestamp() { void pendingToOffline_stampsFirstConnectedAt() { machineIs(DeviceStatus.PENDING); service.updateToOffline(MACHINE, LATER); - assertThat(savedMachine().getFirstConnectedAt()).isEqualTo(LATER); + assertThat(written().getFirstConnectedAt()).isEqualTo(LATER); } @Test @@ -277,9 +307,9 @@ void pendingToOffline_stampsFirstConnectedAt() { void offlineToOnline_leavesFirstConnectedAtUntouched() { Machine m = machine(DeviceStatus.OFFLINE); m.setFirstConnectedAt(EARLIER); - when(machineRepository.findByMachineId(MACHINE)).thenReturn(Optional.of(m)); + storedMachineIs(m); service.updateToOnline(MACHINE, LATER); - assertThat(savedMachine().getFirstConnectedAt()).isEqualTo(EARLIER); + assertThat(written().getFirstConnectedAt()).isEqualTo(EARLIER); } @Test @@ -287,14 +317,88 @@ void offlineToOnline_leavesFirstConnectedAtUntouched() { void pendingToOnline_neverOverwritesAnExistingFirstConnectedAt() { Machine m = machine(DeviceStatus.PENDING); m.setFirstConnectedAt(EARLIER); - when(machineRepository.findByMachineId(MACHINE)).thenReturn(Optional.of(m)); + storedMachineIs(m); + service.updateToOnline(MACHINE, LATER); + assertThat(written().getFirstConnectedAt()).isEqualTo(EARLIER); + } + + @Test + @DisplayName("L1: a status change writes only the fields it owns, so concurrent directory and Fleet writes survive") + void statusChange_writesOnlyStatusFields() { + machineIs(DeviceStatus.PENDING); + service.updateToOnline(MACHINE, LATER); - assertThat(savedMachine().getFirstConnectedAt()).isEqualTo(EARLIER); + + assertThat(writtenPaths()) + .containsExactlyInAnyOrder("status", "telemetryStatus", "lastSeen", "firstConnectedAt"); + } + + @Test + @DisplayName("L2: a machine deleted between the read and the write publishes no application event") + void machineGoneBeforeTheWrite_noEvents() { + machineIs(DeviceStatus.PENDING); + when(machineWriter.update(eq(MACHINE), any(Criteria.class), any(MachineUpdate.class))).thenReturn(Optional.empty()); + + service.updateToOnline(MACHINE, LATER); + + verify(eventPublisher, never()).publishEvent(any()); + } + + @Test + @DisplayName("L4: a transition whose status guard misses still records the event's presence, without status or events") + void statusGuardMissed_presenceStillWritten() { + machineIs(DeviceStatus.OFFLINE); + when(machineWriter.update(eq(MACHINE), any(Criteria.class), any(MachineUpdate.class))).thenReturn(Optional.empty()); + + service.updateToOnline(MACHINE, LATER); + + ArgumentCaptor presence = ArgumentCaptor.forClass(MachineUpdate.class); + verify(machineWriter).update(eq(MACHINE), presence.capture()); + assertThat(presence.getValue().paths()).containsExactlyInAnyOrder("telemetryStatus", "lastSeen"); + Machine written = copyOf(stored); + presence.getValue().applyTo(written); + assertThat(written.getStatus()).isEqualTo(DeviceStatus.OFFLINE); + assertThat(written.getTelemetryStatus()).isEqualTo(TelemetryStatus.ONLINE); + assertThat(written.getLastSeen()).isEqualTo(LATER); + verify(eventPublisher, never()).publishEvent(any()); + } + + // The one MachineWriter.update call, guarded or not + private MachineUpdate writtenUpdate() { + List writes = mockingDetails(machineWriter).getInvocations().stream() + .filter(invocation -> invocation.getMethod().getName().equals("update")) + .map(invocation -> invocation.getArguments()) + .toList(); + assertThat(writes).hasSize(1); + Object[] arguments = writes.getFirst(); + return (MachineUpdate) arguments[arguments.length - 1]; + } + + @Test + @DisplayName("L3: a status transition only lands while the status is still the one it was decided from") + void statusChange_guardedOnThePreviousStatus() { + machineIs(DeviceStatus.OFFLINE); + + service.updateToOnline(MACHINE, LATER); + + ArgumentCaptor guard = ArgumentCaptor.forClass(Criteria.class); + verify(machineWriter).update(eq(MACHINE), guard.capture(), any(MachineUpdate.class)); + assertThat(guard.getValue().getCriteriaObject().get("status")).isEqualTo(DeviceStatus.OFFLINE); + } + + private Set writtenPaths() { + return writtenUpdate().paths(); + } + + private Machine written() { + Machine after = copyOf(stored); + writtenUpdate().applyTo(after); + return after; } - private Machine savedMachine() { - ArgumentCaptor saved = ArgumentCaptor.forClass(Machine.class); - verify(machineRepository).save(saved.capture()); - return saved.getValue(); + private static Machine copyOf(Machine source) { + Machine copy = new Machine(); + BeanUtils.copyProperties(source, copy); + return copy; } } diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/MachineTimezoneServiceTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/MachineTimezoneServiceTest.java index 212261b21d..8d34513e41 100644 --- a/openframe-client-core/src/test/java/com/openframe/client/service/MachineTimezoneServiceTest.java +++ b/openframe-client-core/src/test/java/com/openframe/client/service/MachineTimezoneServiceTest.java @@ -3,9 +3,12 @@ import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.Machine; import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriter; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.junit.jupiter.MockitoExtension; @@ -14,6 +17,8 @@ import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; @@ -24,6 +29,7 @@ class MachineTimezoneServiceTest { private static final String MACHINE_ID = "m-1"; @Mock private MachineRepository machineRepository; + @Mock private MachineWriter machineWriter; @InjectMocks private MachineTimezoneService service; @Test @@ -34,8 +40,13 @@ void validZone_persisted() { service.updateTimezone(MACHINE_ID, "Europe/Kyiv"); - assertThat(machine.getTimezone()).isEqualTo("Europe/Kyiv"); - verify(machineRepository).save(machine); + ArgumentCaptor update = ArgumentCaptor.forClass(MachineUpdate.class); + verify(machineWriter).update(eq(MACHINE_ID), update.capture()); + assertThat(update.getValue().paths()).containsExactly("timezone"); + Machine written = machine("UTC"); + update.getValue().applyTo(written); + assertThat(written.getTimezone()).isEqualTo("Europe/Kyiv"); + verify(machineRepository, never()).save(any()); } @Test @@ -44,7 +55,7 @@ void invalidZone_ignored() { service.updateTimezone(MACHINE_ID, "Not/AZone"); verify(machineRepository, never()).findByMachineId(any()); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); } @Test @@ -53,7 +64,7 @@ void blank_ignored() { service.updateTimezone(MACHINE_ID, " "); verify(machineRepository, never()).findByMachineId(any()); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); } @Test @@ -63,7 +74,7 @@ void unknownMachine_ignored() { service.updateTimezone(MACHINE_ID, "America/New_York"); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); } @Test @@ -74,7 +85,7 @@ void sameValue_noSave() { service.updateTimezone(MACHINE_ID, "Europe/Kyiv"); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); } @Test @@ -86,7 +97,7 @@ void pendingDeletion_ignored() { service.updateTimezone(MACHINE_ID, "Europe/Kyiv"); - verify(machineRepository, never()).save(any()); + verify(machineWriter, never()).update(anyString(), any(MachineUpdate.class)); } private static Machine machine(String timezone) { diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsBackfillServiceTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsBackfillServiceTest.java new file mode 100644 index 0000000000..104cafb5dd --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsBackfillServiceTest.java @@ -0,0 +1,305 @@ +package com.openframe.client.service.agentregistration.fleet; + +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.Machine; +import com.openframe.data.document.tool.ConnectionStatus; +import com.openframe.data.document.tool.ToolConnection; +import com.openframe.data.document.tool.ToolType; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.repository.tool.ToolConnectionRepository; +import com.openframe.data.service.TenantIdProvider; +import com.openframe.sdk.fleetmdm.FleetMdmClient; +import com.openframe.sdk.fleetmdm.exception.FleetMdmException; +import com.openframe.sdk.fleetmdm.model.Host; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InOrder; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; + +import java.time.Duration; +import java.time.Instant; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyInt; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.inOrder; +import static org.mockito.Mockito.lenient; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FleetHostFactsBackfillServiceTest { + + private static final String TENANT_ID = "tenant-1"; + private static final Duration RECHECK_AFTER = Duration.ofDays(7); + + @Mock + private MachineRepository machineRepository; + + @Mock + private ToolConnectionRepository toolConnectionRepository; + + @Mock + private FleetMdmClients fleetMdmClients; + + @Mock + private FleetHostFactsWriter fleetHostFactsWriter; + + @Mock + private TenantIdProvider tenantIdProvider; + + @Mock + private FleetMdmClient fleetClient; + + @InjectMocks + private FleetHostFactsBackfillService service; + + @BeforeEach + void setUp() { + ReflectionTestUtils.setField(service, "recheckAfter", RECHECK_AFTER); + lenient().when(tenantIdProvider.getTenantId()).thenReturn(TENANT_ID); + } + + @Test + void backfill_asksForTheTenantsMachinesCheckedBeforeTheRecheckAge_atMostTheCap() { + // setup + when(machineRepository.findDueForFleetHostFacts(anyString(), any(Instant.class), anyInt())).thenReturn(List.of()); + Instant before = Instant.now(); + + // execution + service.backfill(); + + // verifications + ArgumentCaptor checkedBefore = ArgumentCaptor.forClass(Instant.class); + verify(machineRepository).findDueForFleetHostFacts(eq(TENANT_ID), checkedBefore.capture(), + eq(FleetHostFactsBackfillService.MACHINES_PER_RUN)); + assertThat(checkedBefore.getValue()) + .isBetween(before.minus(RECHECK_AFTER), Instant.now().minus(RECHECK_AFTER)); + } + + @Test + void backfill_nothingDue_noConnectionReadAndNoFleetClient() { + // setup + due(); + + // execution + service.backfill(); + + // verifications + verifyNoInteractions(toolConnectionRepository, fleetMdmClients, fleetHostFactsWriter); + } + + @Test + void backfill_dueMachine_filledFromItsFleetHostAndStamped() { + // setup + Machine blank = machine("m-1"); + Host host = new Host(); + due(blank); + connections(List.of("m-1"), connection("m-1", "11")); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.getHostById(11L)).thenReturn(host); + + // execution + service.backfill(); + + // verifications + verify(fleetHostFactsWriter).fill(blank, host); + verify(machineRepository).markHostFactsChecked(eq("m-1"), any(Instant.class)); + } + + @Test + void backfill_readsOnlyTheConnectedFleetConnectionsOfTheDueMachines() { + // setup + due(machine("m-1"), machine("m-2")); + connections(List.of("m-1", "m-2")); + + // execution + service.backfill(); + + // verifications + verify(toolConnectionRepository).findByTenantIdAndMachineIdInAndToolTypeAndStatus( + TENANT_ID, List.of("m-1", "m-2"), ToolType.FLEET_MDM, ConnectionStatus.CONNECTED); + } + + @Test + void backfill_machineWithoutAFleetConnection_stampedWithoutCallingFleet() { + // setup + due(machine("m-1")); + connections(List.of("m-1")); + + // execution + service.backfill(); + + // verifications + verify(machineRepository).markHostFactsChecked(eq("m-1"), any(Instant.class)); + verifyNoInteractions(fleetMdmClients, fleetHostFactsWriter); + } + + @Test + void backfill_hostNeverConfirmedByFleet_stampedWithoutCallingFleet() { + // setup + due(machine("m-1")); + connections(List.of("m-1"), connection("m-1", "6F1A2B3C-0000-4D5E-8F90-123456789ABC")); + + // execution + service.backfill(); + + // verifications + verify(machineRepository).markHostFactsChecked(eq("m-1"), any(Instant.class)); + verifyNoInteractions(fleetMdmClients, fleetHostFactsWriter); + } + + @Test + void backfill_hostIdTooLongForALong_stampedAndTheOthersStillRead() { + // setup + Machine next = machine("m-2"); + Host host = new Host(); + due(machine("m-1"), next); + connections(List.of("m-1", "m-2"), connection("m-1", "1234567890123456789012345"), connection("m-2", "12")); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.getHostById(12L)).thenReturn(host); + + // execution + service.backfill(); + + // verifications + verify(fleetHostFactsWriter).fill(next, host); + verify(fleetClient, times(1)).getHostById(anyLong()); + verify(machineRepository).markHostFactsChecked(eq("m-1"), any(Instant.class)); + } + + @Test + void backfill_machinesWithoutAHostStampedBeforeTheFleetClientIsCreated_soAMissingFleetDoesNotKeepThemDue() { + // setup + due(machine("m-1"), machine("m-2")); + connections(List.of("m-1", "m-2"), connection("m-2", "12")); + when(fleetMdmClients.client()).thenThrow(new IllegalStateException("Found no tool with id fleetmdm-server")); + + // execution + Throwable thrown = catchThrowable(service::backfill); + + // verifications + assertThat(thrown).isInstanceOf(IllegalStateException.class); + InOrder order = inOrder(machineRepository, fleetMdmClients); + order.verify(machineRepository).markHostFactsChecked(eq("m-1"), any(Instant.class)); + order.verify(fleetMdmClients).client(); + verify(machineRepository, never()).markHostFactsChecked(eq("m-2"), any(Instant.class)); + } + + @Test + void backfill_oneHostLookupFails_theOtherMachinesStillFilled() { + // setup + Machine first = machine("m-1"); + Machine second = machine("m-2"); + Host host = new Host(); + due(first, second); + connections(List.of("m-1", "m-2"), connection("m-1", "11"), connection("m-2", "12")); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.getHostById(11L)).thenThrow(new FleetMdmException("Failed to fetch Fleet host 11")); + when(fleetClient.getHostById(12L)).thenReturn(host); + + // execution + service.backfill(); + + // verifications + verify(fleetHostFactsWriter).fill(second, host); + verify(fleetHostFactsWriter, never()).fill(eq(first), any(Host.class)); + } + + @Test + void backfill_eachCompletedRead_stampedWhetherFleetFilledAnythingOrNot_aFailedReadNot() { + // setup + due(machine("m-1"), machine("m-2"), machine("m-3")); + connections(List.of("m-1", "m-2", "m-3"), + connection("m-1", "11"), connection("m-2", "12"), connection("m-3", "13")); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.getHostById(11L)).thenReturn(new Host()); + when(fleetClient.getHostById(12L)).thenReturn(null); + when(fleetClient.getHostById(13L)).thenThrow(new FleetMdmException("Failed to fetch Fleet host 13")); + Instant before = Instant.now(); + + // execution + service.backfill(); + + // verifications + ArgumentCaptor stamp = ArgumentCaptor.forClass(Instant.class); + verify(machineRepository).markHostFactsChecked(eq("m-1"), stamp.capture()); + verify(machineRepository).markHostFactsChecked(eq("m-2"), any(Instant.class)); + verify(machineRepository, never()).markHostFactsChecked(eq("m-3"), any(Instant.class)); + assertThat(stamp.getValue()).isAfterOrEqualTo(before); + } + + @Test + void backfill_hostGoneFromFleet_nothingWritten() { + // setup + due(machine("m-1")); + connections(List.of("m-1"), connection("m-1", "11")); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.getHostById(11L)).thenReturn(null); + + // execution + service.backfill(); + + // verifications + verifyNoInteractions(fleetHostFactsWriter); + } + + @Test + void backfill_machinesReadInTheOrderTheQueryReturnsThem() { + // setup + Machine neverChecked = machine("m-2"); + Machine checkedLongAgo = machine("m-1"); + due(neverChecked, checkedLongAgo); + connections(List.of("m-2", "m-1"), connection("m-1", "11"), connection("m-2", "12")); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.getHostById(anyLong())).thenReturn(new Host()); + + // execution + service.backfill(); + + // verifications + InOrder order = inOrder(fleetClient); + order.verify(fleetClient).getHostById(12L); + order.verify(fleetClient).getHostById(11L); + } + + private void due(Machine... machines) { + when(machineRepository.findDueForFleetHostFacts(eq(TENANT_ID), any(Instant.class), + eq(FleetHostFactsBackfillService.MACHINES_PER_RUN))).thenReturn(List.of(machines)); + } + + private void connections(List machineIds, ToolConnection... connections) { + when(toolConnectionRepository.findByTenantIdAndMachineIdInAndToolTypeAndStatus( + TENANT_ID, machineIds, ToolType.FLEET_MDM, ConnectionStatus.CONNECTED)).thenReturn(List.of(connections)); + } + + private static ToolConnection connection(String machineId, String agentToolId) { + ToolConnection connection = new ToolConnection(); + connection.setId("c-" + machineId); + connection.setMachineId(machineId); + connection.setToolType(ToolType.FLEET_MDM); + connection.setStatus(ConnectionStatus.CONNECTED); + connection.setAgentToolId(agentToolId); + return connection; + } + + private static Machine machine(String machineId) { + Machine machine = new Machine(); + machine.setMachineId(machineId); + machine.setStatus(DeviceStatus.ONLINE); + return machine; + } +} diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsWriterTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsWriterTest.java new file mode 100644 index 0000000000..f7c94cf2c9 --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetHostFactsWriterTest.java @@ -0,0 +1,182 @@ +package com.openframe.client.service.agentregistration.fleet; + +import com.openframe.data.document.device.Machine; +import com.openframe.data.repository.device.MachineRepository; +import com.openframe.data.service.machine.MachineUpdate; +import com.openframe.data.service.machine.MachineWriter; +import com.openframe.sdk.fleetmdm.model.Host; +import org.bson.Document; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.mongodb.core.query.Criteria; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FleetHostFactsWriterTest { + + private static final String MACHINE_ID = "m-1"; + + @Mock + private MachineRepository machineRepository; + + @Mock + private MachineWriter machineWriter; + + @Captor + private ArgumentCaptor updateCaptor; + + @Captor + private ArgumentCaptor guardCaptor; + + @InjectMocks + private FleetHostFactsWriter writer; + + @Test + void fill_machineWithoutFacts_everyFleetFactWritten() { + // setup + Machine machine = machine(); + Host host = fleetHost(); + + // execution + writer.fill(machine, host); + + // verifications + verify(machineWriter).update(eq(MACHINE_ID), any(Criteria.class), updateCaptor.capture()); + MachineUpdate update = updateCaptor.getValue(); + assertThat(update.paths()).containsExactly("serialNumber", "model", "manufacturer", "osUuid", "computerName"); + Machine written = new Machine(); + update.applyTo(written); + assertThat(written).extracting(Machine::getSerialNumber, Machine::getModel, Machine::getManufacturer, + Machine::getOsUuid, Machine::getComputerName) + .containsExactly("C02XG2JHJG5H", "MacBookPro18,3", "Apple Inc.", + "6F1A2B3C-0000-4D5E-8F90-123456789ABC", "Jane's MacBook Pro"); + } + + @Test + void fill_storedFacts_keptAndOnlyTheBlankOnesWritten() { + // setup + Machine machine = machine(); + machine.setSerialNumber("FROM-AGENT"); + machine.setModel(" "); + machine.setManufacturer("Apple Inc."); + machine.setOsUuid("FROM-AGENT-UUID"); + Host host = fleetHost(); + + // execution + writer.fill(machine, host); + + // verifications + verify(machineWriter).update(eq(MACHINE_ID), any(Criteria.class), updateCaptor.capture()); + assertThat(updateCaptor.getValue().paths()).containsExactly("model", "computerName"); + } + + @Test + void fill_paddedFleetValue_writtenTrimmed() { + // setup + Machine machine = machine(); + Host host = new Host(); + host.setHardwareSerial(" C02XG2JHJG5H \n"); + + // execution + writer.fill(machine, host); + + // verifications + verify(machineWriter).update(eq(MACHINE_ID), any(Criteria.class), updateCaptor.capture()); + Machine written = new Machine(); + updateCaptor.getValue().applyTo(written); + assertThat(written.getSerialNumber()).isEqualTo("C02XG2JHJG5H"); + } + + @Test + void fill_blankFields_writeGuardedOnEachStillBeingBlank() { + // setup + Machine machine = machine(); + machine.setSerialNumber("FROM-AGENT"); + machine.setManufacturer("Apple Inc."); + machine.setOsUuid("FROM-AGENT-UUID"); + machine.setComputerName("Jane's MacBook Pro"); + Host host = fleetHost(); + + // execution + writer.fill(machine, host); + + // verifications + verify(machineWriter).update(eq(MACHINE_ID), guardCaptor.capture(), any(MachineUpdate.class)); + Document stillBlank = new Document("$or", List.of( + new Document("model", new Document("$exists", false)), + new Document("model", null), + new Document("model", ""))); + assertThat(guardCaptor.getValue().getCriteriaObject()) + .isEqualTo(new Document("$and", List.of(stillBlank))); + } + + @Test + void fill_fleetHostWithoutFacts_nothingWritten() { + // setup + Machine machine = machine(); + Host host = new Host(); + host.setHardwareSerial(" "); + + // execution + writer.fill(machine, host); + + // verifications + verifyNoInteractions(machineWriter); + } + + @Test + void fill_byMachineId_storedMachineFilled() { + // setup + Host host = fleetHost(); + when(machineRepository.findByMachineId(MACHINE_ID)).thenReturn(Optional.of(machine())); + + // execution + writer.fill(MACHINE_ID, host); + + // verifications + verify(machineWriter).update(eq(MACHINE_ID), any(Criteria.class), any(MachineUpdate.class)); + } + + @Test + void fill_byMachineIdOfAnUnknownMachine_nothingWritten() { + // setup + Host host = fleetHost(); + when(machineRepository.findByMachineId(MACHINE_ID)).thenReturn(Optional.empty()); + + // execution + writer.fill(MACHINE_ID, host); + + // verifications + verifyNoInteractions(machineWriter); + } + + private static Machine machine() { + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + return machine; + } + + private static Host fleetHost() { + Host host = new Host(); + host.setHardwareSerial("C02XG2JHJG5H"); + host.setHardwareModel("MacBookPro18,3"); + host.setHardwareVendor("Apple Inc."); + host.setUuid("6F1A2B3C-0000-4D5E-8F90-123456789ABC"); + host.setComputerName("Jane's MacBook Pro"); + return host; + } +} diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetMdmClientsTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetMdmClientsTest.java new file mode 100644 index 0000000000..71cf894dc8 --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/fleet/FleetMdmClientsTest.java @@ -0,0 +1,84 @@ +package com.openframe.client.service.agentregistration.fleet; + +import com.openframe.data.document.tool.IntegratedTool; +import com.openframe.data.document.tool.ToolApiKey; +import com.openframe.data.document.tool.ToolCredentials; +import com.openframe.data.document.tool.ToolUrl; +import com.openframe.data.document.tool.ToolUrlType; +import com.openframe.data.service.IntegratedToolService; +import com.openframe.sdk.fleetmdm.FleetMdmClient; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.test.util.ReflectionTestUtils; + +import java.util.List; +import java.util.Optional; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FleetMdmClientsTest { + + @Mock + private IntegratedToolService integratedToolService; + + @Test + void client_noFleetTool_throwsNamingTheTool() { + // setup + FleetMdmClients clients = new FleetMdmClients(integratedToolService); + when(integratedToolService.getToolByKey("fleetmdm-server")).thenReturn(Optional.empty()); + + // execution + Throwable thrown = catchThrowable(clients::client); + + // verifications + assertThat(thrown).isInstanceOf(IllegalStateException.class) + .hasMessage("Found no tool with id fleetmdm-server"); + } + + @Test + void client_fleetTool_builtFromItsApiUrlAndToken() { + // setup + FleetMdmClients clients = spy(new FleetMdmClients(integratedToolService)); + FleetMdmClient built = mock(FleetMdmClient.class); + when(integratedToolService.getToolByKey("fleetmdm-server")).thenReturn(Optional.of(fleetTool())); + doReturn(built).when(clients).createClient("http://fleet:8070", "fleet-token"); + + // execution + FleetMdmClient client = clients.client(); + + // verifications + assertThat(client).isSameAs(built); + } + + @Test + void validateTenantConfig_multiTenancyWithoutTenant_failsAtStartup() { + // setup + FleetMdmClients clients = new FleetMdmClients(integratedToolService); + ReflectionTestUtils.setField(clients, "fleetMultiTenancyEnabled", true); + ReflectionTestUtils.setField(clients, "tenantId", ""); + + // execution + Throwable thrown = catchThrowable(clients::validateTenantConfig); + + // verifications + assertThat(thrown).isInstanceOf(IllegalStateException.class).hasMessage( + "openframe.fleet.multi-tenancy.enabled=true but no tenant id is configured (TENANT_ID env var missing?)"); + } + + private static IntegratedTool fleetTool() { + ToolApiKey apiKey = new ToolApiKey(); + apiKey.setKey("fleet-token"); + ToolCredentials credentials = new ToolCredentials(); + credentials.setApiKey(apiKey); + ToolUrl api = ToolUrl.builder().url("http://fleet").port("8070").type(ToolUrlType.API).build(); + return IntegratedTool.builder().key("fleetmdm-server").toolUrls(List.of(api)).credentials(credentials).build(); + } +} diff --git a/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformerTest.java b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformerTest.java new file mode 100644 index 0000000000..2119b10945 --- /dev/null +++ b/openframe-client-core/src/test/java/com/openframe/client/service/agentregistration/transformer/FleetMdmAgentIdTransformerTest.java @@ -0,0 +1,110 @@ +package com.openframe.client.service.agentregistration.transformer; + +import com.openframe.client.service.agentregistration.fleet.FleetHostFactsWriter; +import com.openframe.client.service.agentregistration.fleet.FleetMdmClients; +import com.openframe.sdk.fleetmdm.FleetMdmClient; +import com.openframe.sdk.fleetmdm.model.Host; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; +import static org.mockito.Mockito.doThrow; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class FleetMdmAgentIdTransformerTest { + + private static final String MACHINE_ID = "m-1"; + private static final String HOST_UUID = "6F1A2B3C-0000-4D5E-8F90-123456789ABC"; + + @Mock + private FleetMdmClients fleetMdmClients; + + @Mock + private FleetHostFactsWriter fleetHostFactsWriter; + + @Mock + private FleetMdmClient fleetClient; + + @InjectMocks + private FleetMdmAgentIdTransformer transformer; + + @Test + void transform_matchingHost_hostIdReturnedAndItsFactsFilled() { + // setup + Host host = enrolledHost(); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.searchHosts(HOST_UUID, 0, 2)).thenReturn(List.of(host)); + + // execution + String hostId = transformer.transform(MACHINE_ID, HOST_UUID, false); + + // verifications + assertThat(hostId).isEqualTo("42"); + verify(fleetHostFactsWriter).fill(MACHINE_ID, host); + } + + @Test + void transform_factsWriteFails_hostIdStillReturned() { + // setup + Host host = enrolledHost(); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.searchHosts(HOST_UUID, 0, 2)).thenReturn(List.of(host)); + doThrow(new IllegalStateException("Mongo unavailable")).when(fleetHostFactsWriter).fill(MACHINE_ID, host); + + // execution + String hostId = transformer.transform(MACHINE_ID, HOST_UUID, false); + + // verifications + assertThat(hostId).isEqualTo("42"); + } + + @Test + void transform_hostNotEnrolledYetOnTheLastAttempt_uuidReturnedAndNothingFilled() { + // setup + Host pending = new Host(); + pending.setId(42L); + pending.setUuid(HOST_UUID); + when(fleetMdmClients.client()).thenReturn(fleetClient); + when(fleetClient.searchHosts(HOST_UUID, 0, 2)).thenReturn(List.of(pending)); + + // execution + String agentToolId = transformer.transform(MACHINE_ID, HOST_UUID, true); + + // verifications + assertThat(agentToolId).isEqualTo(HOST_UUID); + verifyNoInteractions(fleetHostFactsWriter); + } + + @Test + void transform_fleetToolMissing_failsAsBefore() { + // setup + when(fleetMdmClients.client()).thenThrow(new IllegalStateException("Found no tool with id fleetmdm-server")); + + // execution + Throwable thrown = catchThrowable(() -> transformer.transform(MACHINE_ID, HOST_UUID, false)); + + // verifications + assertThat(thrown).isInstanceOf(IllegalStateException.class) + .hasMessage("Failed to transform Fleet MDM agent tool ID"); + verifyNoInteractions(fleetHostFactsWriter); + } + + private static Host enrolledHost() { + Host host = new Host(); + host.setId(42L); + host.setUuid(HOST_UUID); + host.setOsqueryVersion("5.12.1"); + host.setLastEnrolledAt("2026-10-30T09:00:00Z"); + host.setHardwareSerial("C02XG2JHJG5H"); + return host; + } +} diff --git a/openframe-data-device-aspect/src/main/java/com/openframe/data/service/impl/MachineTagEventServiceImpl.java b/openframe-data-device-aspect/src/main/java/com/openframe/data/service/impl/MachineTagEventServiceImpl.java index 4c4415fc24..2a25215f06 100644 --- a/openframe-data-device-aspect/src/main/java/com/openframe/data/service/impl/MachineTagEventServiceImpl.java +++ b/openframe-data-device-aspect/src/main/java/com/openframe/data/service/impl/MachineTagEventServiceImpl.java @@ -1,5 +1,7 @@ package com.openframe.data.service.impl; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.tag.Tag; import com.openframe.data.document.tag.TagAssignment; @@ -355,7 +357,23 @@ private MachinePinotMessage buildMachinePinotMessageFromParts(Machine machine, L .osType(machine.getOsType() != null ? machine.getOsType().name() : null) .tags(tagKeyNames) .tagKeyValues(tagKeyValues) + .directorySources(directorySourceNames(machine)) + .directoryUserLink(directoryUserLinkName(machine)) .ingestionTime(System.currentTimeMillis()) .build(); } + + private static List directorySourceNames(Machine machine) { + List sources = machine.getDirectorySources(); + if (sources == null) { + return List.of(); + } + return sources.stream().map(Enum::name).toList(); + } + + // Sent as NONE rather than null, so the USER facet counts a machine without a link instead of dropping it + private static String directoryUserLinkName(Machine machine) { + DirectoryUserLink link = machine.getDirectoryUserLink(); + return link != null ? link.name() : DirectoryUserLink.NONE.name(); + } } diff --git a/openframe-data-kafka/src/main/java/com/openframe/kafka/model/MachinePinotMessage.java b/openframe-data-kafka/src/main/java/com/openframe/kafka/model/MachinePinotMessage.java index 87d0c8ac84..89d94db7fc 100644 --- a/openframe-data-kafka/src/main/java/com/openframe/kafka/model/MachinePinotMessage.java +++ b/openframe-data-kafka/src/main/java/com/openframe/kafka/model/MachinePinotMessage.java @@ -25,5 +25,7 @@ public class MachinePinotMessage implements KafkaMessage { private String osType; private List tags; // tag key names for Pinot MV column private List tagKeyValues; // "key:value" pairs for Pinot indexing + private List directorySources; // DirectorySource names for the Pinot MV column; [] when none + private String directoryUserLink; // DirectoryUserLink name; NONE when the machine has no link private long ingestionTime; } diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/DirectorySource.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/DirectorySource.java new file mode 100644 index 0000000000..ceeb167d70 --- /dev/null +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/DirectorySource.java @@ -0,0 +1,7 @@ +package com.openframe.data.document.device; + +// A directory that knows the machine besides the agent. Only an external directory integration writes it. +public enum DirectorySource { + MICROSOFT_365, + GOOGLE_WORKSPACE +} diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/DirectoryUserLink.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/DirectoryUserLink.java new file mode 100644 index 0000000000..72fff5d336 --- /dev/null +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/DirectoryUserLink.java @@ -0,0 +1,9 @@ +package com.openframe.data.document.device; + +// Who the machine is tied to in a directory: PRIMARY is one user, SHARED is several, NONE is nobody. A machine an external +// directory integration never wrote (every machine in OSS) has no value, and every reader takes that as NONE. +public enum DirectoryUserLink { + PRIMARY, + SHARED, + NONE +} diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/Machine.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/Machine.java index 71e477b786..4ffff7ae2d 100644 --- a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/Machine.java +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/Machine.java @@ -40,11 +40,13 @@ public class Machine implements TenantScoped { private String organizationId; private String userId; // User who installed the agent; optional, absent for older registrations private String hostname; + private String computerName; // Fleet computer_name, filled where blank; not exposed in GraphQL private String displayName; private String nickname; private String serialNumber; private String manufacturer; private String model; + private Instant hostFactsCheckedAt; // last time the Fleet host facts backfill tried this machine; null = never @Indexed private DeviceType type; @Indexed @@ -59,6 +61,12 @@ public class Machine implements TenantScoped { private Instant lastSecurityScan; private Instant lastComplianceScan; private List complianceRequirements; + // Directory summary of the machine's linked directory records. Only an external directory integration writes it, + // so it stays null in OSS, and GraphQL reads null as [] / NONE. + private List directorySources; + private DirectoryUserLink directoryUserLink; + private List directoryUserIds; // directory account ids, the primary user first + private String directoryUserName; // display name of the user when PRIMARY @CreatedDate private Instant registeredAt; // When device was first registered (replaces createdAt) @LastModifiedDate diff --git a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/filter/MachineQueryFilter.java b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/filter/MachineQueryFilter.java index a37fa13b05..8b549c79b2 100644 --- a/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/filter/MachineQueryFilter.java +++ b/openframe-data-mongo-common/src/main/java/com/openframe/data/document/device/filter/MachineQueryFilter.java @@ -1,5 +1,7 @@ package com.openframe.data.document.device.filter; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.packagesearch.PackageManagerType; import com.openframe.data.document.rmm.script.OsType; import lombok.AllArgsConstructor; @@ -27,6 +29,9 @@ public class MachineQueryFilter { private List nicknames; private List tagKeys; private List tagValues; + // The directory summary an external directory integration writes; both empty in OSS. NONE also matches a machine never written. + private List directorySources; + private List directoryUserLinks; public MachineQueryFilter(List statuses, List excludeStatuses, List deviceTypes, List osTypes, List organizationIds, diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepository.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepository.java index b728c1b4a8..6bffe19b98 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepository.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepository.java @@ -44,6 +44,12 @@ List findAvailableForScheduleWithCursor(String tenantId, MachineQueryFi */ void updateLastSeen(String machineId, Instant lastSeen); + // Bypasses save and MachineWriter like updateLastSeen: the marker is not part of the Pinot payload + void markHostFactsChecked(String machineId, Instant checkedAt); + + // Live machines missing a Fleet host fact, never checked or checked before checkedBefore: never checked first + List findDueForFleetHostFacts(String tenantId, Instant checkedBefore, int limit); + boolean isSortableField(String field); String getDefaultSortField(); diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepositoryImpl.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepositoryImpl.java index 06f8749ee5..2a9af629e9 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepositoryImpl.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/device/CustomMachineRepositoryImpl.java @@ -1,6 +1,8 @@ package com.openframe.data.repository.device; import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.device.filter.DeviceFacetDimension; import com.openframe.data.document.device.filter.MachineQueryFilter; @@ -38,6 +40,7 @@ import java.util.stream.IntStream; import java.util.stream.Stream; +import static com.openframe.data.service.machine.MachineFields.FLEET_HOST_FACTS; import static java.util.stream.Collectors.joining; import static java.util.stream.Collectors.toMap; import static org.springframework.util.CollectionUtils.isEmpty; @@ -51,11 +54,14 @@ public class CustomMachineRepositoryImpl implements CustomMachineRepository { private static final String OS_TYPE_FIELD = "osType"; private static final String MACHINE_ID_FIELD = "machineId"; private static final String LAST_SEEN_FIELD = "lastSeen"; + private static final String HOST_FACTS_CHECKED_AT_FIELD = "hostFactsCheckedAt"; private static final String VERSION_FIELD = "version"; private static final String STATUS_FIELD = "status"; private static final String TYPE_FIELD = "type"; private static final String ORGANIZATION_ID_FIELD = "organizationId"; private static final String PACKAGE_MANAGERS_FIELD = "packageManagers"; + private static final String DIRECTORY_SOURCES_FIELD = "directorySources"; + private static final String DIRECTORY_USER_LINK_FIELD = "directoryUserLink"; private static final String COUNT_FIELD = "count"; private static final String BUCKET_FIELD = "_availableBucket"; private static final String ONLINE_STATUS = "ONLINE"; @@ -80,6 +86,8 @@ public class CustomMachineRepositoryImpl implements CustomMachineRepository { private static final int UNKNOWN_STATUS_RANK = 0; private static final String TENANT_ID_FIELD = "tenantId"; + private static final List RETIRED_STATUSES = + List.of(DeviceStatus.PENDING_DELETION, DeviceStatus.DELETED, DeviceStatus.ARCHIVED); private final MongoTemplate mongoTemplate; @@ -632,6 +640,7 @@ Query buildDeviceQuery(MachineQueryFilter filter, String search, String excludeF criteriaList.add(softwareManageableCriteria(manageableBy)); } addNameCriteria(criteriaList, filter); + addDirectoryCriteria(criteriaList, filter); } if (search != null && !search.isEmpty()) { @@ -643,7 +652,8 @@ Query buildDeviceQuery(MachineQueryFilter filter, String search, String excludeF Criteria.where("ip").regex(quoted, "i"), Criteria.where("serialNumber").regex(quoted, "i"), Criteria.where("manufacturer").regex(quoted, "i"), - Criteria.where("model").regex(quoted, "i") + Criteria.where("model").regex(quoted, "i"), + Criteria.where("directoryUserName").regex(quoted, "i") )); } @@ -670,6 +680,24 @@ private void addNameCriteria(List criteriaList, MachineQueryFilter fil } } + // NONE is also every machine no directory integration wrote, and every machine in OSS: $in with null matches a + // missing field as well as an explicit null + private static void addDirectoryCriteria(List criteriaList, MachineQueryFilter filter) { + List sources = filter.getDirectorySources(); + if (!isEmpty(sources)) { + criteriaList.add(Criteria.where(DIRECTORY_SOURCES_FIELD).in(sources)); + } + List links = filter.getDirectoryUserLinks(); + if (isEmpty(links)) { + return; + } + List matching = new ArrayList<>(links); + if (links.contains(DirectoryUserLink.NONE)) { + matching.add(null); + } + criteriaList.add(Criteria.where(DIRECTORY_USER_LINK_FIELD).in(matching)); + } + private List exactNameCriteria(MachineQueryFilter filter) { List hostnames = filter.getHostnames(); List nicknames = filter.getNicknames(); @@ -715,6 +743,41 @@ public void updateLastSeen(String machineId, Instant lastSeen) { mongoTemplate.updateFirst(query, update, Machine.class); } + @Override + public void markHostFactsChecked(String machineId, Instant checkedAt) { + Query query = new Query(Criteria.where(MACHINE_ID_FIELD).is(machineId)); + // $inc by 0 as in updateLastSeen: a background stamp never conflicts with a user edit. + Update update = new Update().set(HOST_FACTS_CHECKED_AT_FIELD, checkedAt).inc(VERSION_FIELD, 0); + mongoTemplate.updateFirst(query, update, Machine.class); + } + + // No index serves "any fact blank": the filter runs server side over the tenant's machines, once per backfill run + @Override + public List findDueForFleetHostFacts(String tenantId, Instant checkedBefore, int limit) { + Assert.hasText(tenantId, "tenantId must not be blank"); + Assert.notNull(checkedBefore, "checkedBefore must not be null"); + Assert.isTrue(limit > 0, "limit must be positive"); + Criteria missingAnyFact = new Criteria().orOperator(FLEET_HOST_FACTS.stream() + .map(fact -> blank(fact.path())) + .toArray(Criteria[]::new)); + Criteria due = new Criteria().orOperator( + Criteria.where(HOST_FACTS_CHECKED_AT_FIELD).is(null), + Criteria.where(HOST_FACTS_CHECKED_AT_FIELD).lt(checkedBefore)); + Query query = new Query(new Criteria().andOperator( + Criteria.where(TENANT_ID_FIELD).is(tenantId), + Criteria.where(STATUS_FIELD).nin(RETIRED_STATUSES), + missingAnyFact, + due)) + .with(Sort.by(Sort.Direction.ASC, HOST_FACTS_CHECKED_AT_FIELD, MACHINE_ID_FIELD)) + .limit(limit); + return mongoTemplate.find(query, Machine.class); + } + + // Blank as the Fleet host facts writer's guard reads it: absent, null or empty + private static Criteria blank(String path) { + return new Criteria().orOperator(Criteria.where(path).is(null), Criteria.where(path).is("")); + } + @Override public boolean isSortableField(String field) { return field != null && SORTABLE_FIELDS.contains(field.trim()); diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/tool/ToolConnectionRepository.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/tool/ToolConnectionRepository.java index f8d8ee3a82..3987f0f765 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/tool/ToolConnectionRepository.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/repository/tool/ToolConnectionRepository.java @@ -1,10 +1,12 @@ package com.openframe.data.repository.tool; +import com.openframe.data.document.tool.ConnectionStatus; import com.openframe.data.document.tool.ToolConnection; import com.openframe.data.document.tool.ToolType; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.stereotype.Repository; +import java.util.Collection; import java.util.List; import java.util.Optional; @@ -31,4 +33,9 @@ Optional findFirstByTenantIdAndToolTypeAndAgentToolIdOrderByConn List findByToolType(ToolType toolType); List findByAgentToolIdInAndToolType(List agentToolIds, ToolType toolType); + + // The Fleet host facts backfill reads the connections of the machines it is due to try, through the + // tenant_machine_tool_idx index + List findByTenantIdAndMachineIdInAndToolTypeAndStatus( + String tenantId, Collection machineIds, ToolType toolType, ConnectionStatus status); } diff --git a/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/machine/MachineFields.java b/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/machine/MachineFields.java index 2f09975ffa..6783987dd8 100644 --- a/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/machine/MachineFields.java +++ b/openframe-data-mongo-sync/src/main/java/com/openframe/data/service/machine/MachineFields.java @@ -2,6 +2,8 @@ import com.openframe.data.document.device.DeviceStatus; import com.openframe.data.document.device.DeviceType; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.device.TelemetryStatus; import com.openframe.data.document.packagesearch.PackageManagerState; @@ -9,6 +11,7 @@ import com.openframe.data.document.rmm.script.OsType; import java.time.Instant; +import java.util.List; import java.util.Map; import static com.openframe.data.service.machine.MachineField.field; @@ -20,16 +23,40 @@ public final class MachineFields { public static final MachineField DISPLAY_NAME = field("displayName", Machine::setDisplayName); public static final MachineField HOSTNAME = field("hostname", Machine::setHostname); public static final MachineField STATUS = field("status", Machine::setStatus); - public static final MachineField TELEMETRY_STATUS = field("telemetryStatus", Machine::setTelemetryStatus); + public static final MachineField TELEMETRY_STATUS = + field("telemetryStatus", Machine::setTelemetryStatus); + public static final MachineField FIRST_CONNECTED_AT = field("firstConnectedAt", Machine::setFirstConnectedAt); public static final MachineField TYPE = field("type", Machine::setType); public static final MachineField LAST_SEEN = field("lastSeen", Machine::setLastSeen); public static final MachineField ORGANIZATION_ID = field("organizationId", Machine::setOrganizationId); public static final MachineField AGENT_VERSION = field("agentVersion", Machine::setAgentVersion); public static final MachineField OS_TYPE = field("osType", Machine::setOsType); + public static final MachineField USER_ID = field("userId", Machine::setUserId); + public static final MachineField TIMEZONE = field("timezone", Machine::setTimezone); public static final MachineField STUCK_NOTIFIED_AT = field("stuckNotifiedAt", Machine::setStuckNotifiedAt); public static final MachineField> PACKAGE_MANAGERS = field("packageManagers", Machine::setPackageManagers); + // Hardware facts: copied from the registration request, then filled from the Fleet host where still blank + public static final MachineField SERIAL_NUMBER = field("serialNumber", Machine::setSerialNumber); + public static final MachineField MODEL = field("model", Machine::setModel); + public static final MachineField MANUFACTURER = field("manufacturer", Machine::setManufacturer); + public static final MachineField OS_UUID = field("osUuid", Machine::setOsUuid); + public static final MachineField COMPUTER_NAME = field("computerName", Machine::setComputerName); + // The facts the Fleet host facts backfill looks for: a machine missing any of them is due a Fleet read + public static final List> FLEET_HOST_FACTS = + List.of(SERIAL_NUMBER, MODEL, MANUFACTURER, OS_UUID, COMPUTER_NAME); + + // Directory summary: written only by an external directory integration + public static final MachineField> DIRECTORY_SOURCES = + field("directorySources", Machine::setDirectorySources); + public static final MachineField DIRECTORY_USER_LINK = + field("directoryUserLink", Machine::setDirectoryUserLink); + public static final MachineField> DIRECTORY_USER_IDS = + field("directoryUserIds", Machine::setDirectoryUserIds); + public static final MachineField DIRECTORY_USER_NAME = + field("directoryUserName", Machine::setDirectoryUserName); + public static final MachineField UPDATED_AT = field("updatedAt", Machine::setUpdatedAt); private MachineFields() { diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/integration/repository/tool/ToolConnectionRepositoryIT.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/integration/repository/tool/ToolConnectionRepositoryIT.java new file mode 100644 index 0000000000..e5671976fc --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/integration/repository/tool/ToolConnectionRepositoryIT.java @@ -0,0 +1,84 @@ +package com.openframe.data.integration.repository.tool; + +import com.mongodb.client.MongoClient; +import com.mongodb.client.MongoClients; +import com.openframe.data.document.tool.ConnectionStatus; +import com.openframe.data.document.tool.ToolConnection; +import com.openframe.data.document.tool.ToolType; +import com.openframe.data.integration.BaseMongoIntegrationTest; +import com.openframe.data.repository.tool.ToolConnectionRepository; +import org.junit.jupiter.api.AfterAll; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.repository.support.MongoRepositoryFactory; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.tuple; + +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class ToolConnectionRepositoryIT extends BaseMongoIntegrationTest { + + private static MongoClient client; + private static MongoTemplate template; + private static ToolConnectionRepository repository; + + @BeforeAll + static void setUp() { + String uri = System.getProperty("mongo.external.uri"); + if (uri == null) { + if (!MONGO.isRunning()) { + MONGO.start(); + } + uri = MONGO.getConnectionString() + "/?directConnection=true"; + } + client = MongoClients.create(uri); + template = new MongoTemplate(client, "test"); + MongoRepositoryFactory factory = new MongoRepositoryFactory(template); + repository = factory.getRepository(ToolConnectionRepository.class); + } + + @AfterAll + static void tearDown() { + client.close(); + } + + @BeforeEach + void clean() { + template.dropCollection(ToolConnection.class); + } + + @Test + void findByTenantIdAndMachineIdInAndToolTypeAndStatus_onlyTheGivenMachinesConnectedFleetRowsOfTheTenant() { + // setup + save("tenant-1", "m-1", ToolType.FLEET_MDM, ConnectionStatus.CONNECTED); + save("tenant-1", "m-2", ToolType.FLEET_MDM, ConnectionStatus.DISCONNECTED); + save("tenant-1", "m-3", ToolType.MESHCENTRAL, ConnectionStatus.CONNECTED); + save("tenant-1", "m-4", ToolType.FLEET_MDM, ConnectionStatus.CONNECTED); + save("tenant-2", "m-1", ToolType.FLEET_MDM, ConnectionStatus.CONNECTED); + + // execution + List connections = repository.findByTenantIdAndMachineIdInAndToolTypeAndStatus( + "tenant-1", List.of("m-1", "m-2", "m-3"), ToolType.FLEET_MDM, ConnectionStatus.CONNECTED); + + // verifications + assertThat(connections).extracting(ToolConnection::getTenantId, ToolConnection::getMachineId) + .containsExactly(tuple("tenant-1", "m-1")); + } + + private ToolConnection save(String tenantId, String machineId, ToolType toolType, ConnectionStatus status) { + ToolConnection connection = new ToolConnection(); + connection.setTenantId(tenantId); + connection.setMachineId(machineId); + connection.setToolType(toolType); + connection.setStatus(status); + connection.setAgentToolId("42"); + return template.save(connection); + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryDirectoryFilterIT.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryDirectoryFilterIT.java new file mode 100644 index 0000000000..1838873abd --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryDirectoryFilterIT.java @@ -0,0 +1,108 @@ +package com.openframe.data.repository.device; + +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; +import com.openframe.data.document.device.Machine; +import com.openframe.data.document.device.filter.MachineQueryFilter; +import com.openframe.data.integration.BaseMongoIntegrationTest; +import com.openframe.data.integration.support.MachineIntegrationTestApplication; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.mongodb.core.MongoTemplate; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +// The NONE rule rests on Mongo's $in-with-null semantics and on enum conversion inside the $in, which a query-shape +// test cannot prove. +@SpringBootTest(classes = MachineIntegrationTestApplication.class) +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class CustomMachineRepositoryDirectoryFilterIT extends BaseMongoIntegrationTest { + + private static final String TENANT = "tenant-1"; + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private MachineRepository repository; + + @BeforeEach + void setUp() { + mongoTemplate.dropCollection(Machine.class); + save("m-primary", List.of(DirectorySource.MICROSOFT_365), DirectoryUserLink.PRIMARY, "Jane Doe"); + save("m-shared", List.of(DirectorySource.MICROSOFT_365), DirectoryUserLink.SHARED, null); + save("m-none", List.of(), DirectoryUserLink.NONE, null); + save("m-unwritten", null, null, null); + } + + @Test + void findMachineIds_userLinkNone_explicitNoneAndNeverWrittenMachines() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directoryUserLinks(List.of(DirectoryUserLink.NONE)).build(); + + // execution + List machineIds = repository.findMachineIds(TENANT, filter, ""); + + // verifications + assertThat(machineIds).containsExactlyInAnyOrder("m-none", "m-unwritten"); + } + + @Test + void findMachineIds_userLinkPrimary_onlyThePrimaryMachine() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directoryUserLinks(List.of(DirectoryUserLink.PRIMARY)).build(); + + // execution + List machineIds = repository.findMachineIds(TENANT, filter, ""); + + // verifications + assertThat(machineIds).containsExactly("m-primary"); + } + + @Test + void findMachineIds_directorySourceMicrosoft_machinesMicrosoftKnows() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directorySources(List.of(DirectorySource.MICROSOFT_365)).build(); + + // execution + List machineIds = repository.findMachineIds(TENANT, filter, ""); + + // verifications + assertThat(machineIds).containsExactlyInAnyOrder("m-primary", "m-shared"); + } + + @Test + void findMachineIds_searchByUserName_theMachineOfThatUser() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder().build(); + + // execution + List machineIds = repository.findMachineIds(TENANT, filter, "jane"); + + // verifications + assertThat(machineIds).containsExactly("m-primary"); + } + + private void save(String machineId, List sources, DirectoryUserLink link, String userName) { + Machine machine = new Machine(); + machine.setMachineId(machineId); + machine.setTenantId(TENANT); + machine.setStatus(DeviceStatus.ONLINE); + machine.setHostname("host-" + machineId); + machine.setDirectorySources(sources); + machine.setDirectoryUserLink(link); + machine.setDirectoryUserName(userName); + mongoTemplate.save(machine); + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryDueForFleetHostFactsIT.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryDueForFleetHostFactsIT.java new file mode 100644 index 0000000000..cea45ac5a3 --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryDueForFleetHostFactsIT.java @@ -0,0 +1,178 @@ +package com.openframe.data.repository.device; + +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.Machine; +import com.openframe.data.integration.BaseMongoIntegrationTest; +import com.openframe.data.integration.support.MachineIntegrationTestApplication; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; +import org.junit.jupiter.params.provider.ValueSource; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Criteria; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; + +import java.time.Duration; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +// The Fleet host facts backfill reads only what this query returns, so the query alone decides which machines Fleet +// is asked about, and in which order. +@SpringBootTest(classes = MachineIntegrationTestApplication.class) +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class CustomMachineRepositoryDueForFleetHostFactsIT extends BaseMongoIntegrationTest { + + private static final String TENANT_ID = "tenant-1"; + private static final Instant NOW = Instant.parse("2026-11-02T12:15:00Z"); + private static final Instant CUTOFF = NOW.minus(Duration.ofDays(7)); + private static final int LIMIT = 200; + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private MachineRepository repository; + + @BeforeEach + void setUp() { + mongoTemplate.dropCollection(Machine.class); + } + + @Test + void findDueForFleetHostFacts_machineWithEveryFact_notDue() { + // setup + save(fullyKnown("m-1")); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, LIMIT); + + // verifications + assertThat(due).isEmpty(); + } + + @ParameterizedTest(name = "{0} absent") + @ValueSource(strings = {"serialNumber", "model", "manufacturer", "osUuid", "computerName"}) + void findDueForFleetHostFacts_oneFactAbsent_due(String fact) { + // setup + save(fullyKnown("m-1")); + mongoTemplate.updateFirst(byMachineId("m-1"), new Update().unset(fact), Machine.class); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, LIMIT); + + // verifications + assertThat(due).extracting(Machine::getMachineId).containsExactly("m-1"); + } + + @ParameterizedTest(name = "{0} empty") + @ValueSource(strings = {"serialNumber", "model", "manufacturer", "osUuid", "computerName"}) + void findDueForFleetHostFacts_oneFactEmpty_due(String fact) { + // setup + save(fullyKnown("m-1")); + mongoTemplate.updateFirst(byMachineId("m-1"), new Update().set(fact, ""), Machine.class); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, LIMIT); + + // verifications + assertThat(due).extracting(Machine::getMachineId).containsExactly("m-1"); + } + + @ParameterizedTest + @EnumSource(value = DeviceStatus.class, names = {"PENDING_DELETION", "DELETED", "ARCHIVED"}) + void findDueForFleetHostFacts_retiredMachine_notDue(DeviceStatus status) { + // setup + Machine retired = blank("m-1"); + retired.setStatus(status); + save(retired); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, LIMIT); + + // verifications + assertThat(due).isEmpty(); + } + + @Test + void findDueForFleetHostFacts_checkedSinceTheCutoff_notDue_checkedBefore_due() { + // setup + save(checkedAt(blank("m-recent"), CUTOFF.plus(Duration.ofHours(1)))); + save(checkedAt(blank("m-stale"), CUTOFF.minus(Duration.ofHours(1)))); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, LIMIT); + + // verifications + assertThat(due).extracting(Machine::getMachineId).containsExactly("m-stale"); + } + + @Test + void findDueForFleetHostFacts_neverCheckedFirst_thenTheOldestCheck_atMostTheLimit() { + // setup + save(checkedAt(blank("m-a"), CUTOFF.minus(Duration.ofDays(1)))); + save(checkedAt(blank("m-b"), CUTOFF.minus(Duration.ofDays(3)))); + save(blank("m-c")); + save(checkedAt(blank("m-d"), CUTOFF.minus(Duration.ofDays(2)))); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, 3); + + // verifications + assertThat(due).extracting(Machine::getMachineId).containsExactly("m-c", "m-b", "m-d"); + } + + @Test + void findDueForFleetHostFacts_anotherTenantsMachine_notDue() { + // setup + Machine foreign = blank("m-1"); + foreign.setTenantId("tenant-2"); + save(foreign); + + // execution + List due = repository.findDueForFleetHostFacts(TENANT_ID, CUTOFF, LIMIT); + + // verifications + assertThat(due).isEmpty(); + } + + private void save(Machine machine) { + mongoTemplate.save(machine); + } + + private static Query byMachineId(String machineId) { + return new Query(Criteria.where("machineId").is(machineId)); + } + + private static Machine checkedAt(Machine machine, Instant checkedAt) { + machine.setHostFactsCheckedAt(checkedAt.truncatedTo(ChronoUnit.MILLIS)); + return machine; + } + + private static Machine fullyKnown(String machineId) { + Machine machine = blank(machineId); + machine.setSerialNumber("C02XG2JHJG5H"); + machine.setModel("MacBookPro18,3"); + machine.setManufacturer("Apple Inc."); + machine.setOsUuid("6F1A2B3C-0000-4D5E-8F90-123456789ABC"); + machine.setComputerName("Jane's MacBook Pro"); + return machine; + } + + private static Machine blank(String machineId) { + Machine machine = new Machine(); + machine.setMachineId(machineId); + machine.setTenantId(TENANT_ID); + machine.setStatus(DeviceStatus.ONLINE); + return machine; + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryHostFactsCheckedIT.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryHostFactsCheckedIT.java new file mode 100644 index 0000000000..6f81a0f2b2 --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryHostFactsCheckedIT.java @@ -0,0 +1,90 @@ +package com.openframe.data.repository.device; + +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; +import com.openframe.data.document.device.Machine; +import com.openframe.data.integration.BaseMongoIntegrationTest; +import com.openframe.data.integration.support.MachineIntegrationTestApplication; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.mongodb.core.MongoTemplate; + +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +// The backfill marker is stamped on every attempt, so it must touch nothing else the machine carries. +@SpringBootTest(classes = MachineIntegrationTestApplication.class) +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class CustomMachineRepositoryHostFactsCheckedIT extends BaseMongoIntegrationTest { + + private static final String MACHINE_ID = "m-1"; + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private MachineRepository repository; + + @BeforeEach + void setUp() { + mongoTemplate.dropCollection(Machine.class); + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + machine.setTenantId("tenant-1"); + machine.setStatus(DeviceStatus.ONLINE); + machine.setSerialNumber("C02XG2JHJG5H"); + machine.setDirectorySources(List.of(DirectorySource.MICROSOFT_365)); + machine.setDirectoryUserLink(DirectoryUserLink.PRIMARY); + mongoTemplate.save(machine); + } + + @Test + void markHostFactsChecked_stampsTheMarkerOnly() { + // setup + Instant checkedAt = Instant.parse("2026-10-30T03:15:00Z").truncatedTo(ChronoUnit.MILLIS); + + // execution + repository.markHostFactsChecked(MACHINE_ID, checkedAt); + + // verifications + Machine stored = repository.findByMachineId(MACHINE_ID).orElseThrow(); + assertThat(stored.getHostFactsCheckedAt()).isEqualTo(checkedAt); + assertThat(stored).extracting(Machine::getStatus, Machine::getSerialNumber, Machine::getDirectorySources, + Machine::getDirectoryUserLink) + .containsExactly(DeviceStatus.ONLINE, "C02XG2JHJG5H", List.of(DirectorySource.MICROSOFT_365), + DirectoryUserLink.PRIMARY); + } + + @Test + void markHostFactsChecked_knownMachine_leavesTheVersion() { + // setup + Long savedVersion = repository.findByMachineId(MACHINE_ID).orElseThrow().getVersion(); + + // execution + repository.markHostFactsChecked(MACHINE_ID, Instant.now()); + + // verifications + assertThat(repository.findByMachineId(MACHINE_ID).orElseThrow().getVersion()).isEqualTo(savedVersion); + } + + @Test + void markHostFactsChecked_unknownMachine_createsNothing() { + // setup + + // execution + repository.markHostFactsChecked("m-unknown", Instant.now()); + + // verifications + assertThat(repository.findByMachineId("m-unknown")).isEmpty(); + assertThat(repository.count()).isEqualTo(1); + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryHostFactsCheckedTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryHostFactsCheckedTest.java new file mode 100644 index 0000000000..3674d0cecd --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositoryHostFactsCheckedTest.java @@ -0,0 +1,49 @@ +package com.openframe.data.repository.device; + +import com.openframe.data.document.device.Machine; +import org.bson.Document; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Captor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.data.mongodb.core.MongoTemplate; +import org.springframework.data.mongodb.core.query.Query; +import org.springframework.data.mongodb.core.query.Update; + +import java.time.Instant; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; + +@ExtendWith(MockitoExtension.class) +class CustomMachineRepositoryHostFactsCheckedTest { + + private static final String MACHINE_ID = "m-1"; + private static final Instant CHECKED_AT = Instant.parse("2026-10-30T03:15:00Z"); + + @Mock private MongoTemplate mongoTemplate; + + @Captor private ArgumentCaptor queryCaptor; + @Captor private ArgumentCaptor updateCaptor; + + @InjectMocks private CustomMachineRepositoryImpl repository; + + @Test + void markHostFactsChecked_knownMachine_stampsTheMarkerAndHoldsTheVersion() { + // setup + + // execution + repository.markHostFactsChecked(MACHINE_ID, CHECKED_AT); + + // verifications + verify(mongoTemplate).updateFirst(queryCaptor.capture(), updateCaptor.capture(), eq(Machine.class)); + assertThat(queryCaptor.getValue().getQueryObject()).containsEntry("machineId", MACHINE_ID); + Document update = updateCaptor.getValue().getUpdateObject(); + assertThat(update.get("$set", Document.class)).containsEntry("hostFactsCheckedAt", CHECKED_AT); + assertThat(update.get("$inc", Document.class)).containsEntry("version", 0); + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositorySearchTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositorySearchTest.java index de9eb5b4e4..5a5488509f 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositorySearchTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/repository/device/CustomMachineRepositorySearchTest.java @@ -1,5 +1,7 @@ package com.openframe.data.repository.device; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.document.device.filter.MachineQueryFilter; import com.openframe.data.document.tag.Tag; @@ -20,6 +22,7 @@ import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Query; +import java.util.Arrays; import java.util.List; import java.util.regex.Pattern; import java.util.stream.IntStream; @@ -336,7 +339,7 @@ void findMachines_missingTenant_rejectsBeforeReadingAnyCollection(String tenantI @ParameterizedTest @ValueSource(strings = {"(a+)+$", "web-*", "db?prod"}) - void buildDeviceQuery_dashboardSearch_keepsLiteralSubstringAcrossSevenFields(String search) { + void buildDeviceQuery_dashboardSearch_keepsLiteralSubstringAcrossEightFields(String search) { // setup MachineQueryFilter filter = MachineQueryFilter.builder().build(); @@ -346,11 +349,82 @@ void buildDeviceQuery_dashboardSearch_keepsLiteralSubstringAcrossSevenFields(Str // verifications assertThat(clauses(query.getQueryObject()).filter(clause -> clause.values().stream().anyMatch(Pattern.class::isInstance))) .flatExtracting(Document::keySet) - .containsExactlyInAnyOrder("hostname", "nickname", "displayName", "ip", "serialNumber", "manufacturer", "model"); + .containsExactlyInAnyOrder("hostname", "nickname", "displayName", "ip", "serialNumber", "manufacturer", + "model", "directoryUserName"); assertThat(nameRegex(query, "hostname").matcher("prefix-" + search + "-suffix").find()).isTrue(); assertThat(nameRegex(query, "hostname").matcher("web-prod").find()).isFalse(); } + @Test + void buildDeviceQuery_userNameSearch_matchesTheDirectoryUserCaseInsensitively() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder().build(); + + // execution + Query query = repository.buildDeviceQuery(filter, "jane"); + + // verifications + assertThat(nameRegex(query, "directoryUserName").matcher("Jane Doe").find()).isTrue(); + assertThat(nameRegex(query, "directoryUserName").matcher("John Smith").find()).isFalse(); + } + + @Test + void buildDeviceQuery_directorySources_inClauseOnTheStoredSources() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directorySources(List.of(DirectorySource.MICROSOFT_365)).build(); + + // execution + Query query = repository.buildDeviceQuery(filter, ""); + + // verifications + assertThat(clauseFor(query, "directorySources")) + .containsEntry("directorySources", new Document("$in", List.of(DirectorySource.MICROSOFT_365))); + } + + @Test + void buildDeviceQuery_userLinksWithNone_alsoMatchesMachinesWithoutALink() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directoryUserLinks(List.of(DirectoryUserLink.SHARED, DirectoryUserLink.NONE)).build(); + + // execution + Query query = repository.buildDeviceQuery(filter, ""); + + // verifications + List sharedOrNone = Arrays.asList(DirectoryUserLink.SHARED, DirectoryUserLink.NONE, null); + assertThat(clauseFor(query, "directoryUserLink")) + .containsEntry("directoryUserLink", new Document("$in", sharedOrNone)); + } + + @Test + void buildDeviceQuery_userLinksWithoutNone_onlyThoseLinks() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directoryUserLinks(List.of(DirectoryUserLink.PRIMARY)).build(); + + // execution + Query query = repository.buildDeviceQuery(filter, ""); + + // verifications + assertThat(clauseFor(query, "directoryUserLink")) + .containsEntry("directoryUserLink", new Document("$in", List.of(DirectoryUserLink.PRIMARY))); + } + + @Test + void buildDeviceQuery_emptyDirectoryFilters_noDirectoryClause() { + // setup + MachineQueryFilter filter = MachineQueryFilter.builder() + .directorySources(List.of()).directoryUserLinks(List.of()).build(); + + // execution + Query query = repository.buildDeviceQuery(filter, ""); + + // verifications + assertThat(clauses(query.getQueryObject())) + .noneMatch(clause -> clause.containsKey("directorySources") || clause.containsKey("directoryUserLink")); + } + @Test void machineQueryFilter_legacyConstructor_preservesExistingArguments() { // setup diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterRoundTripIT.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterRoundTripIT.java new file mode 100644 index 0000000000..7ba5a5bf6c --- /dev/null +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterRoundTripIT.java @@ -0,0 +1,114 @@ +package com.openframe.data.service.machine; + +import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; +import com.openframe.data.document.device.Machine; +import com.openframe.data.integration.BaseMongoIntegrationTest; +import com.openframe.data.integration.support.MachineIntegrationTestApplication; +import com.openframe.data.repository.device.MachineRepository; +import org.bson.Document; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Tag; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.condition.EnabledIfSystemProperty; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.data.mongodb.core.MongoTemplate; + +import java.util.List; + +import static com.openframe.data.service.machine.MachineFields.COMPUTER_NAME; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_SOURCES; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_IDS; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_LINK; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_NAME; +import static com.openframe.data.service.machine.MachineFields.MANUFACTURER; +import static com.openframe.data.service.machine.MachineFields.MODEL; +import static com.openframe.data.service.machine.MachineFields.OS_UUID; +import static com.openframe.data.service.machine.MachineFields.SERIAL_NUMBER; +import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; +import static org.assertj.core.api.Assertions.assertThat; +import static org.mockito.Mockito.mock; + +// An external directory integration writes the directory summary through MachineWriter, and the OSS GraphQL and Mongo device filters +// read it back, so the stored shape is the contract: enums by name, lists as arrays. +@SpringBootTest(classes = MachineIntegrationTestApplication.class) +@Tag("integration") +@EnabledIfSystemProperty(named = "integration.tests", matches = "true") +class MachineWriterRoundTripIT extends BaseMongoIntegrationTest { + + private static final String MACHINE_ID = "m-1"; + + @Autowired + private MongoTemplate mongoTemplate; + + @Autowired + private MachineRepository repository; + + private MachineWriter writer; + + // Publishing off: no OutboxPublisher bean. + @SuppressWarnings("unchecked") + private static ObjectProvider absent() { + return mock(ObjectProvider.class); + } + + @BeforeEach + void setUp() { + mongoTemplate.dropCollection(Machine.class); + writer = new MachineWriter(mongoTemplate, absent(), absent()); + Machine machine = new Machine(); + machine.setMachineId(MACHINE_ID); + machine.setTenantId("tenant-1"); + machine.setStatus(DeviceStatus.ONLINE); + machine.setHostname("janes-mbp"); + mongoTemplate.save(machine); + } + + @Test + void update_hardwareAndDirectoryFields_readBackAsWrittenWithEnumsStoredByName() { + // setup + MachineUpdate update = machineUpdate() + .set(SERIAL_NUMBER, "C02XG2JHJG5H") + .set(MODEL, "MacBookPro18,3") + .set(MANUFACTURER, "Apple Inc.") + .set(OS_UUID, "6F1A2B3C-0000-4D5E-8F90-123456789ABC") + .set(COMPUTER_NAME, "Jane's MacBook Pro") + .set(DIRECTORY_SOURCES, List.of(DirectorySource.MICROSOFT_365)) + .set(DIRECTORY_USER_LINK, DirectoryUserLink.SHARED) + .set(DIRECTORY_USER_IDS, List.of("acc-1", "acc-2")) + .set(DIRECTORY_USER_NAME, null); + + // execution + writer.update(MACHINE_ID, update); + + // verifications + Machine stored = repository.findByMachineId(MACHINE_ID).orElseThrow(); + assertThat(stored).extracting(Machine::getSerialNumber, Machine::getModel, Machine::getManufacturer, + Machine::getOsUuid, Machine::getComputerName, Machine::getHostname) + .containsExactly("C02XG2JHJG5H", "MacBookPro18,3", "Apple Inc.", + "6F1A2B3C-0000-4D5E-8F90-123456789ABC", "Jane's MacBook Pro", "janes-mbp"); + assertThat(stored).extracting(Machine::getDirectorySources, Machine::getDirectoryUserLink, + Machine::getDirectoryUserIds, Machine::getDirectoryUserName) + .containsExactly(List.of(DirectorySource.MICROSOFT_365), DirectoryUserLink.SHARED, + List.of("acc-1", "acc-2"), null); + Document raw = mongoTemplate.getCollection("machines").find(new Document("machineId", MACHINE_ID)).first(); + assertThat(raw.getList("directorySources", String.class)).containsExactly("MICROSOFT_365"); + assertThat(raw.getString("directoryUserLink")).isEqualTo("SHARED"); + } + + @Test + void findByMachineId_machineSavedBeforeTheFieldsExisted_readsThemAsNull() { + // setup + + // execution + Machine stored = repository.findByMachineId(MACHINE_ID).orElseThrow(); + + // verifications + assertThat(stored).extracting(Machine::getComputerName, Machine::getDirectorySources, + Machine::getDirectoryUserLink, Machine::getDirectoryUserIds, Machine::getDirectoryUserName) + .containsOnlyNulls(); + } +} diff --git a/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterTest.java b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterTest.java index ddf5dd2351..cbe115bf0d 100644 --- a/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterTest.java +++ b/openframe-data-mongo-sync/src/test/java/com/openframe/data/service/machine/MachineWriterTest.java @@ -1,6 +1,8 @@ package com.openframe.data.service.machine; import com.openframe.data.document.device.DeviceStatus; +import com.openframe.data.document.device.DirectorySource; +import com.openframe.data.document.device.DirectoryUserLink; import com.openframe.data.document.device.Machine; import com.openframe.data.repository.device.publishing.MachineAggregateSpec; import com.openframe.data.repository.device.publishing.MachineEvent; @@ -26,8 +28,17 @@ import java.util.Set; import java.util.stream.Collectors; +import static com.openframe.data.service.machine.MachineFields.COMPUTER_NAME; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_SOURCES; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_IDS; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_LINK; +import static com.openframe.data.service.machine.MachineFields.DIRECTORY_USER_NAME; import static com.openframe.data.service.machine.MachineFields.LAST_SEEN; +import static com.openframe.data.service.machine.MachineFields.MANUFACTURER; +import static com.openframe.data.service.machine.MachineFields.MODEL; import static com.openframe.data.service.machine.MachineFields.NICKNAME; +import static com.openframe.data.service.machine.MachineFields.OS_UUID; +import static com.openframe.data.service.machine.MachineFields.SERIAL_NUMBER; import static com.openframe.data.service.machine.MachineFields.STATUS; import static com.openframe.data.service.machine.MachineUpdate.machineUpdate; import static org.assertj.core.api.Assertions.assertThat; @@ -178,6 +189,55 @@ void emptyUpdateDoesNothing() { verifyNoInteractions(template); } + @Test + @DisplayName("hardware facts and the directory summary are writable fields: each lands in $set under its own path and on the after image") + void writesHardwareAndDirectoryFields() { + storedDocumentIs(new Machine()); + + MachineWriteResult result = writer.update("m1", machineUpdate() + .set(SERIAL_NUMBER, "C02XG2JHJG5H") + .set(MODEL, "MacBookPro18,3") + .set(MANUFACTURER, "Apple Inc.") + .set(OS_UUID, "6F1A2B3C-0000-4D5E-8F90-123456789ABC") + .set(COMPUTER_NAME, "Jane's MacBook Pro") + .set(DIRECTORY_SOURCES, List.of(DirectorySource.MICROSOFT_365)) + .set(DIRECTORY_USER_LINK, DirectoryUserLink.PRIMARY) + .set(DIRECTORY_USER_IDS, List.of("acc-1")) + .set(DIRECTORY_USER_NAME, "Jane Doe")) + .orElseThrow(); + + assertThat(setClause(capturedUpdate())).containsOnlyKeys("serialNumber", "model", "manufacturer", "osUuid", + "computerName", "directorySources", "directoryUserLink", "directoryUserIds", "directoryUserName", + "updatedAt"); + Machine after = result.after(); + assertThat(after).extracting(Machine::getSerialNumber, Machine::getModel, Machine::getManufacturer, + Machine::getOsUuid, Machine::getComputerName) + .containsExactly("C02XG2JHJG5H", "MacBookPro18,3", "Apple Inc.", + "6F1A2B3C-0000-4D5E-8F90-123456789ABC", "Jane's MacBook Pro"); + assertThat(after).extracting(Machine::getDirectorySources, Machine::getDirectoryUserLink, + Machine::getDirectoryUserIds, Machine::getDirectoryUserName) + .containsExactly(List.of(DirectorySource.MICROSOFT_365), DirectoryUserLink.PRIMARY, + List.of("acc-1"), "Jane Doe"); + } + + @Test + @DisplayName("clearing the directory summary writes explicit nulls, so a machine whose links went away reads as NONE again") + void clearsDirectoryFields() { + storedDocumentIs(new Machine()); + + writer.update("m1", machineUpdate() + .set(DIRECTORY_SOURCES, null) + .set(DIRECTORY_USER_LINK, null) + .set(DIRECTORY_USER_IDS, null) + .set(DIRECTORY_USER_NAME, null)); + + assertThat(setClause(capturedUpdate())) + .containsEntry("directorySources", null) + .containsEntry("directoryUserLink", null) + .containsEntry("directoryUserIds", null) + .containsEntry("directoryUserName", null); + } + // Heartbeat and status writes change no copied name, so they stay out of the outbox transaction. @Test void aStatusWrite_isNotPublished_evenWithPublishingOn() { diff --git a/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotClientDeviceRepository.java b/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotClientDeviceRepository.java index 4b9d89e04f..b78cc1c94c 100644 --- a/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotClientDeviceRepository.java +++ b/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotClientDeviceRepository.java @@ -23,6 +23,8 @@ public class PinotClientDeviceRepository extends AbstractPinotRepository impleme private static final String ORGANIZATION_ID = "organizationId"; private static final String TAGS = "tags"; private static final String TAG_KEY_VALUES = "tagKeyValues"; + private static final String DIRECTORY_SOURCES = "directorySources"; + private static final String DIRECTORY_USER_LINK = "directoryUserLink"; /** * Statuses considered "active" for the organization device counts facet @@ -55,8 +57,11 @@ public Map getStatusFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues) { - return executeFacetQuery(STATUS, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, STATUS); + List tagKeyValues, + List directorySources, + List userLinks) { + return executeFacetQuery(STATUS, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, STATUS); } @Override @@ -67,8 +72,11 @@ public Map getDeviceTypeFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues) { - return executeFacetQuery(DEVICE_TYPE, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, DEVICE_TYPE); + List tagKeyValues, + List directorySources, + List userLinks) { + return executeFacetQuery(DEVICE_TYPE, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, DEVICE_TYPE); } @Override @@ -79,8 +87,11 @@ public Map getOsTypeFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues) { - return executeFacetQuery(OS_TYPE, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, OS_TYPE); + List tagKeyValues, + List directorySources, + List userLinks) { + return executeFacetQuery(OS_TYPE, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, OS_TYPE); } @Override @@ -91,9 +102,12 @@ public Map getOrganizationFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues) { + List tagKeyValues, + List directorySources, + List userLinks) { // Organization device counts only include active devices (ONLINE / OFFLINE). - return executeActiveFacetQuery(ORGANIZATION_ID, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, ORGANIZATION_ID); + return executeActiveFacetQuery(ORGANIZATION_ID, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, + tagKeyValues, directorySources, userLinks, ORGANIZATION_ID); } @Override @@ -104,8 +118,44 @@ public Map getTagKeyFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues) { - return executeFacetQuery(TAG_KEY_VALUES, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, TAG_KEY_VALUES); + List tagKeyValues, + List directorySources, + List userLinks) { + return executeFacetQuery(TAG_KEY_VALUES, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, + tagKeyValues, directorySources, userLinks, TAG_KEY_VALUES); + } + + @Override + public Map getDirectorySourceFilterOptions( + String tenantId, + List statuses, + List deviceTypes, + List osTypes, + List organizationIds, + List tagKeys, + List tagKeyValues, + List directorySources, + List userLinks) { + // A machine no directory knows stores [""] (the column's defaultNullValue), which executeKeyCountQuery skips. + return executeFacetQuery(DIRECTORY_SOURCES, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, + tagKeyValues, directorySources, userLinks, DIRECTORY_SOURCES); + } + + @Override + public Map getUserLinkFilterOptions( + String tenantId, + List statuses, + List deviceTypes, + List osTypes, + List organizationIds, + List tagKeys, + List tagKeyValues, + List directorySources, + List userLinks) { + // A machine no external directory integration wrote reads NONE (the column's defaultNullValue), so it is + // counted. + return executeFacetQuery(DIRECTORY_USER_LINK, tenantId, statuses, deviceTypes, osTypes, organizationIds, tagKeys, + tagKeyValues, directorySources, userLinks, DIRECTORY_USER_LINK); } @Override @@ -116,10 +166,13 @@ public int getFilteredDeviceCount( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues) { + List tagKeyValues, + List directorySources, + List userLinks) { PinotQueryBuilder queryBuilder = new PinotQueryBuilder(devicesTable, tenantId) .selectCountAll(); - applyDeviceFilters(queryBuilder, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, null); + applyDeviceFilters(queryBuilder, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, null); return executeCountQuery(queryBuilder.build()); } @@ -137,9 +190,12 @@ private Map executeFacetQuery(String facetField, List organizationIds, List tagKeys, List tagKeyValues, + List directorySources, + List userLinks, String excludeField) { PinotQueryBuilder queryBuilder = newFacetQueryBuilder(facetField, tenantId); - applyDeviceFilters(queryBuilder, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, excludeField); + applyDeviceFilters(queryBuilder, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, excludeField); return executeKeyCountQuery(queryBuilder.build()); } @@ -155,9 +211,12 @@ private Map executeActiveFacetQuery(String facetField, List organizationIds, List tagKeys, List tagKeyValues, + List directorySources, + List userLinks, String excludeField) { PinotQueryBuilder queryBuilder = newFacetQueryBuilder(facetField, tenantId); - applyActiveDeviceFilters(queryBuilder, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, excludeField); + applyActiveDeviceFilters(queryBuilder, statuses, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, excludeField); return executeKeyCountQuery(queryBuilder.build()); } @@ -184,13 +243,16 @@ private void applyDeviceFilters(PinotQueryBuilder queryBuilder, List organizationIds, List tagKeys, List tagKeyValues, + List directorySources, + List userLinks, String excludeField) { List requestedStatuses = sanitizeStatuses(statuses); if (!requestedStatuses.contains(DELETED.name())) { queryBuilder.whereNotEquals(STATUS, DELETED.name()); } applyStatusFilter(queryBuilder, requestedStatuses, excludeField); - applyNonStatusFilters(queryBuilder, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, excludeField); + applyNonStatusFilters(queryBuilder, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, excludeField); } /** @@ -205,10 +267,13 @@ private void applyActiveDeviceFilters(PinotQueryBuilder queryBuilder, List organizationIds, List tagKeys, List tagKeyValues, + List directorySources, + List userLinks, String excludeField) { queryBuilder.whereIn(STATUS, ACTIVE_STATUSES); applyStatusFilter(queryBuilder, sanitizeStatuses(statuses), excludeField); - applyNonStatusFilters(queryBuilder, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, excludeField); + applyNonStatusFilters(queryBuilder, deviceTypes, osTypes, organizationIds, tagKeys, tagKeyValues, + directorySources, userLinks, excludeField); } private static List sanitizeStatuses(List statuses) { @@ -241,6 +306,8 @@ private void applyNonStatusFilters(PinotQueryBuilder queryBuilder, List organizationIds, List tagKeys, List tagKeyValues, + List directorySources, + List userLinks, String excludeField) { if (!DEVICE_TYPE.equals(excludeField) && deviceTypes != null && !deviceTypes.isEmpty()) { queryBuilder.whereOr(DEVICE_TYPE, deviceTypes); @@ -261,5 +328,14 @@ private void applyNonStatusFilters(PinotQueryBuilder queryBuilder, if (!TAG_KEY_VALUES.equals(excludeField) && tagKeyValues != null && !tagKeyValues.isEmpty()) { queryBuilder.whereOr(TAG_KEY_VALUES, tagKeyValues); } + + // MV column: "directorySources = 'X'" holds when any of the machine's sources is X + if (!DIRECTORY_SOURCES.equals(excludeField) && directorySources != null && !directorySources.isEmpty()) { + queryBuilder.whereOr(DIRECTORY_SOURCES, directorySources); + } + + if (!DIRECTORY_USER_LINK.equals(excludeField) && userLinks != null && !userLinks.isEmpty()) { + queryBuilder.whereOr(DIRECTORY_USER_LINK, userLinks); + } } } diff --git a/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotDeviceRepository.java b/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotDeviceRepository.java index e9cf52b044..b0b12297b7 100644 --- a/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotDeviceRepository.java +++ b/openframe-data-pinot/src/main/java/com/openframe/data/pinot/repository/PinotDeviceRepository.java @@ -12,7 +12,9 @@ Map getStatusFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues + List tagKeyValues, + List directorySources, + List userLinks ); Map getDeviceTypeFilterOptions( @@ -22,7 +24,9 @@ Map getDeviceTypeFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues + List tagKeyValues, + List directorySources, + List userLinks ); Map getOsTypeFilterOptions( @@ -32,7 +36,9 @@ Map getOsTypeFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues + List tagKeyValues, + List directorySources, + List userLinks ); Map getOrganizationFilterOptions( @@ -42,7 +48,9 @@ Map getOrganizationFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues + List tagKeyValues, + List directorySources, + List userLinks ); /** @@ -55,7 +63,39 @@ Map getTagKeyFilterOptions( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues + List tagKeyValues, + List directorySources, + List userLinks + ); + + /** + * SOURCES filter options from the directorySources MV column. A machine no directory knows adds no bucket. + */ + Map getDirectorySourceFilterOptions( + String tenantId, + List statuses, + List deviceTypes, + List osTypes, + List organizationIds, + List tagKeys, + List tagKeyValues, + List directorySources, + List userLinks + ); + + /** + * USER filter options from the directoryUserLink column. A machine no external directory integration wrote is NONE. + */ + Map getUserLinkFilterOptions( + String tenantId, + List statuses, + List deviceTypes, + List osTypes, + List organizationIds, + List tagKeys, + List tagKeyValues, + List directorySources, + List userLinks ); int getFilteredDeviceCount( @@ -65,6 +105,8 @@ int getFilteredDeviceCount( List osTypes, List organizationIds, List tagKeys, - List tagKeyValues + List tagKeyValues, + List directorySources, + List userLinks ); } diff --git a/openframe-data-pinot/src/test/java/com/openframe/data/pinot/repository/PinotClientDeviceRepositoryTest.java b/openframe-data-pinot/src/test/java/com/openframe/data/pinot/repository/PinotClientDeviceRepositoryTest.java index 35cb5fde79..ccf85dba48 100644 --- a/openframe-data-pinot/src/test/java/com/openframe/data/pinot/repository/PinotClientDeviceRepositoryTest.java +++ b/openframe-data-pinot/src/test/java/com/openframe/data/pinot/repository/PinotClientDeviceRepositoryTest.java @@ -18,6 +18,7 @@ import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.junit.jupiter.api.Assertions.assertTrue; import static org.mockito.ArgumentMatchers.anyString; @@ -55,7 +56,7 @@ class TenantIdValidation { void throwsOnNullTenant() { assertThrows(PinotQueryException.class, () -> repository.getStatusFilterOptions(null, List.of(), List.of(), List.of(), - List.of(), List.of(), List.of())); + List.of(), List.of(), List.of(), List.of(), List.of())); } @Test @@ -63,7 +64,7 @@ void throwsOnNullTenant() { void countThrowsOnBlankTenant() { assertThrows(PinotQueryException.class, () -> repository.getFilteredDeviceCount(" ", List.of(), List.of(), List.of(), - List.of(), List.of(), List.of())); + List.of(), List.of(), List.of(), List.of(), List.of())); } @Test @@ -71,15 +72,17 @@ void countThrowsOnBlankTenant() { void allFacetQueriesIncludeTenant() { whenQueryReturnsEmptyRows(); - repository.getStatusFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); - repository.getDeviceTypeFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); - repository.getOsTypeFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); - repository.getOrganizationFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); - repository.getTagKeyFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); - repository.getFilteredDeviceCount(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getStatusFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getDeviceTypeFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getOsTypeFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getOrganizationFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getTagKeyFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getDirectorySourceFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getUserLinkFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + repository.getFilteredDeviceCount(TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); ArgumentCaptor captor = ArgumentCaptor.forClass(String.class); - verify(pinotConnection, org.mockito.Mockito.times(6)).execute(captor.capture()); + verify(pinotConnection, org.mockito.Mockito.times(8)).execute(captor.capture()); for (String query : captor.getAllValues()) { assertTrue(query.contains("tenantId = 'uuid-aaa'"), "Query missing tenantId: " + query); @@ -96,7 +99,7 @@ class FacetQueryStructure { void statusFacetStructure() { whenQueryReturnsEmptyRows(); repository.getStatusFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), - List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); assertTrue(query.contains("SELECT status, COUNT(*) as count"), "was: " + query); assertTrue(query.contains("GROUP BY status"), "was: " + query); @@ -108,7 +111,7 @@ void statusFacetStructure() { void organizationFacetStructure() { whenQueryReturnsEmptyRows(); repository.getOrganizationFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), - List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); assertTrue(query.contains("SELECT organizationId, COUNT(*) as count")); assertTrue(query.contains("GROUP BY organizationId")); @@ -119,7 +122,7 @@ void organizationFacetStructure() { void excludesDeletedDevices() { whenQueryReturnsEmptyRows(); repository.getStatusFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), - List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); assertTrue(query.contains("status != 'DELETED'"), "was: " + query); } @@ -134,7 +137,7 @@ class ExcludeFieldBehavior { void statusFacetSkipsStatusFilter() { whenQueryReturnsEmptyRows(); repository.getStatusFilterOptions(TENANT_ID, List.of("ACTIVE"), - List.of("LAPTOP"), List.of(), List.of(), List.of(), List.of()); + List.of("LAPTOP"), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); // deviceType filter should be applied assertTrue(query.contains("deviceType = 'LAPTOP'"), "deviceType missing: " + query); @@ -148,7 +151,7 @@ void statusFacetSkipsStatusFilter() { void deviceTypeFacetSkipsDeviceTypeFilter() { whenQueryReturnsEmptyRows(); repository.getDeviceTypeFilterOptions(TENANT_ID, List.of(), - List.of("LAPTOP"), List.of("WINDOWS"), List.of(), List.of(), List.of()); + List.of("LAPTOP"), List.of("WINDOWS"), List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); // osType filter applied assertTrue(query.contains("osType = 'WINDOWS'"), "osType missing: " + query); @@ -162,7 +165,7 @@ void deviceTypeFacetSkipsDeviceTypeFilter() { void statusFilterWithDeletedLiftsBaseGuard() { whenQueryReturnsEmptyRows(); repository.getDeviceTypeFilterOptions(TENANT_ID, List.of("ACTIVE", "DELETED"), - List.of(), List.of(), List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); // The user's selection is applied verbatim (no status is silently dropped)... assertTrue(query.contains("status = 'ACTIVE'"), "was: " + query); @@ -176,7 +179,7 @@ void statusFilterWithDeletedLiftsBaseGuard() { void statusFilterDeletedOnly() { whenQueryReturnsEmptyRows(); repository.getDeviceTypeFilterOptions(TENANT_ID, List.of("DELETED"), - List.of(), List.of(), List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); assertTrue(!query.contains("status != 'DELETED'"), "base guard should be lifted: " + query); assertTrue(query.contains("status = 'DELETED'"), "was: " + query); @@ -196,7 +199,7 @@ void countReturnsFromFirstCell() { when(resultSet.getLong(0, 0)).thenReturn(42L); int count = repository.getFilteredDeviceCount(TENANT_ID, List.of(), List.of(), List.of(), - List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of()); assertEquals(42, count); } @@ -212,7 +215,7 @@ void facetMapsRowsToMap() { when(resultSet.getLong(1, 1)).thenReturn(5L); Map result = repository.getStatusFilterOptions( - TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + TENANT_ID, List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); assertEquals(2, result.size()); assertEquals(10, result.get("ACTIVE")); @@ -227,7 +230,7 @@ void countReturnsZeroOnEmpty() { when(resultSet.getRowCount()).thenReturn(0); int count = repository.getFilteredDeviceCount(TENANT_ID, List.of(), List.of(), List.of(), - List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of()); assertEquals(0, count); } } @@ -241,13 +244,86 @@ class SqlInjection { void tenantIdEscaped() { whenQueryReturnsEmptyRows(); repository.getFilteredDeviceCount("evil'; DROP TABLE devices;--", - List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); + List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of(), List.of()); String query = captureQuery(); assertTrue(query.contains("tenantId = 'evil''; DROP TABLE devices;--'"), "Quotes not escaped: " + query); } } + @Nested + @DisplayName("directory summary: SOURCES and USER facets and filters") + class DirectoryFacets { + + @Test + @DisplayName("getDirectorySourceFilterOptions groups by the multi-value directorySources column") + void directorySourceFacetStructure() { + whenQueryReturnsEmptyRows(); + repository.getDirectorySourceFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), + List.of(), List.of(), List.of(), List.of()); + String query = captureQuery(); + assertTrue(query.contains("SELECT directorySources, COUNT(*) as count"), "was: " + query); + assertTrue(query.contains("GROUP BY directorySources"), "was: " + query); + assertTrue(query.contains("status != 'DELETED'"), "was: " + query); + } + + @Test + @DisplayName("getUserLinkFilterOptions groups by directoryUserLink") + void userLinkFacetStructure() { + whenQueryReturnsEmptyRows(); + repository.getUserLinkFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), + List.of(), List.of(), List.of(), List.of()); + String query = captureQuery(); + assertTrue(query.contains("SELECT directoryUserLink, COUNT(*) as count"), "was: " + query); + assertTrue(query.contains("GROUP BY directoryUserLink"), "was: " + query); + } + + @Test + @DisplayName("the filtered count applies both directory filters") + void countAppliesDirectoryFilters() { + whenQueryReturnsEmptyRows(); + repository.getFilteredDeviceCount(TENANT_ID, List.of(), List.of(), List.of(), List.of(), + List.of(), List.of(), List.of("MICROSOFT_365"), List.of("PRIMARY", "NONE")); + String query = captureQuery(); + assertTrue(query.contains("(directorySources = 'MICROSOFT_365')"), "was: " + query); + assertTrue(query.contains("(directoryUserLink = 'PRIMARY' OR directoryUserLink = 'NONE')"), + "was: " + query); + } + + @Test + @DisplayName("the USER facet skips its own filter and keeps the SOURCES one") + void userLinkFacetSkipsItsOwnFilter() { + whenQueryReturnsEmptyRows(); + repository.getUserLinkFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), + List.of(), List.of(), List.of("MICROSOFT_365"), List.of("PRIMARY")); + String query = captureQuery(); + assertTrue(query.contains("directorySources = 'MICROSOFT_365'"), "was: " + query); + assertFalse(query.contains("directoryUserLink = 'PRIMARY'"), "own filter must be skipped: " + query); + } + + @Test + @DisplayName("the SOURCES facet skips its own filter and keeps the USER one") + void directorySourceFacetSkipsItsOwnFilter() { + whenQueryReturnsEmptyRows(); + repository.getDirectorySourceFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), + List.of(), List.of(), List.of("MICROSOFT_365"), List.of("SHARED")); + String query = captureQuery(); + assertTrue(query.contains("directoryUserLink = 'SHARED'"), "was: " + query); + assertFalse(query.contains("directorySources = 'MICROSOFT_365'"), "own filter must be skipped: " + query); + } + + @Test + @DisplayName("the other facets honour both directory filters, the active-only organization facet included") + void otherFacetsApplyDirectoryFilters() { + whenQueryReturnsEmptyRows(); + repository.getOrganizationFilterOptions(TENANT_ID, List.of(), List.of(), List.of(), List.of(), + List.of(), List.of(), List.of("MICROSOFT_365"), List.of("SHARED")); + String query = captureQuery(); + assertTrue(query.contains("directorySources = 'MICROSOFT_365'"), "was: " + query); + assertTrue(query.contains("directoryUserLink = 'SHARED'"), "was: " + query); + } + } + // ----- helpers ----- private void whenQueryReturnsEmptyRows() { diff --git a/openframe-external-api-service-core/src/main/java/com/openframe/external/controller/DeviceController.java b/openframe-external-api-service-core/src/main/java/com/openframe/external/controller/DeviceController.java index fc6129e92e..8ec9e6a0f0 100644 --- a/openframe-external-api-service-core/src/main/java/com/openframe/external/controller/DeviceController.java +++ b/openframe-external-api-service-core/src/main/java/com/openframe/external/controller/DeviceController.java @@ -1,6 +1,7 @@ package com.openframe.external.controller; import com.openframe.api.dto.device.DeviceFilterCriteria; +import com.openframe.api.dto.device.DeviceFilterFacet; import com.openframe.api.dto.shared.CursorPaginationCriteria; import com.openframe.api.dto.shared.SortInput; import com.openframe.api.exception.DeviceNotFoundException; @@ -201,7 +202,7 @@ public DeviceFilterResponse getDeviceFilters( .tagValues(tagValues) .build(); var filters = deviceFilterService.getDeviceFilters( - filterCriteria).join(); + filterCriteria, DeviceFilterFacet.REST).join(); return deviceMapper.toDeviceFilterResponse(filters); } diff --git a/openframe-external-api-service-core/src/test/java/com/openframe/external/controller/DeviceControllerTest.java b/openframe-external-api-service-core/src/test/java/com/openframe/external/controller/DeviceControllerTest.java index c59c0e27d1..fa78d2d2e1 100644 --- a/openframe-external-api-service-core/src/test/java/com/openframe/external/controller/DeviceControllerTest.java +++ b/openframe-external-api-service-core/src/test/java/com/openframe/external/controller/DeviceControllerTest.java @@ -2,6 +2,7 @@ import com.openframe.api.dto.CountedGenericQueryResult; import com.openframe.api.dto.device.DeviceFilterCriteria; +import com.openframe.api.dto.device.DeviceFilterFacet; import com.openframe.api.dto.device.DeviceFilterOption; import com.openframe.api.dto.device.DeviceFilters; import com.openframe.api.dto.device.TagFilterOption; @@ -35,9 +36,11 @@ import org.springframework.test.web.servlet.request.MockHttpServletRequestBuilder; import java.time.Instant; +import java.util.EnumSet; import java.util.List; import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.concurrent.CompletableFuture; import static org.junit.jupiter.api.Assertions.assertEquals; @@ -261,7 +264,7 @@ void unknownDeviceIs404WithDeviceNotFoundCodeAndTagsAreNotLoaded() throws Except @Test void filtersPassEveryParamToTheDomainAndRenameOrganizationsToCustomers() throws Exception { - when(deviceFilterService.getDeviceFilters(any(DeviceFilterCriteria.class))).thenReturn(CompletableFuture.completedFuture( + when(deviceFilterService.getDeviceFilters(any(DeviceFilterCriteria.class), any())).thenReturn(CompletableFuture.completedFuture( DeviceFilters.builder() .statuses(List.of(new DeviceFilterOption("ONLINE", "Online", 4))) .deviceTypes(List.of(new DeviceFilterOption("LAPTOP", "Laptop", 3))) @@ -294,7 +297,7 @@ void filtersPassEveryParamToTheDomainAndRenameOrganizationsToCustomers() throws .andExpect(jsonPath("$.filteredCount").value(9)); ArgumentCaptor filter = ArgumentCaptor.forClass(DeviceFilterCriteria.class); - verify(deviceFilterService).getDeviceFilters(filter.capture()); + verify(deviceFilterService).getDeviceFilters(filter.capture(), any()); assertEquals(DeviceFilterCriteria.builder() .statuses(List.of(DeviceStatus.ONLINE)) .deviceTypes(List.of(DeviceType.LAPTOP)) @@ -306,6 +309,27 @@ void filtersPassEveryParamToTheDomainAndRenameOrganizationsToCustomers() throws verifyNoInteractions(deviceService); } + @Test + void filtersAskOnlyForTheFacetsTheResponseExposesAndSkipTheDirectoryOnes() throws Exception { + when(deviceFilterService.getDeviceFilters(any(DeviceFilterCriteria.class), any())).thenReturn( + CompletableFuture.completedFuture(DeviceFilters.builder().filteredCount(0).build())); + + mockMvc.perform(get(BASE + "/filters")).andExpect(status().isOk()); + + @SuppressWarnings("unchecked") + ArgumentCaptor> facets = ArgumentCaptor.forClass(Set.class); + verify(deviceFilterService).getDeviceFilters(any(DeviceFilterCriteria.class), facets.capture()); + assertFalse(facets.getValue().contains(DeviceFilterFacet.DIRECTORY_SOURCES)); + assertFalse(facets.getValue().contains(DeviceFilterFacet.USER_LINKS)); + assertEquals(EnumSet.of( + DeviceFilterFacet.STATUSES, + DeviceFilterFacet.DEVICE_TYPES, + DeviceFilterFacet.OS_TYPES, + DeviceFilterFacet.ORGANIZATION_IDS, + DeviceFilterFacet.TAG_KEYS, + DeviceFilterFacet.FILTERED_COUNT), facets.getValue()); + } + @Test void filtersWithUnknownStatusAre400TypeMismatch() throws Exception { mockMvc.perform(get(BASE + "/filters").param("statuses", "BOGUS")) diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/index.ts b/openframe-frontend-core/src/components/features/cloud-tenants/index.ts index 24b7debc25..987cac139d 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/index.ts +++ b/openframe-frontend-core/src/components/features/cloud-tenants/index.ts @@ -1,27 +1,32 @@ 'use client'; -export { TenantsTableView } from './tenants-table-view'; -export type { TenantsTableViewProps } from './tenants-table-view'; +export { TENANTS_TABLE_FILTER_COLUMNS, TenantsTableView } from './tenants-table-view'; +export type { TenantsTableFilterColumn, TenantsTableFilters, TenantsTableViewProps } from './tenants-table-view'; export { TenantCell } from './tenant-cell'; export type { TenantCellProps } from './tenant-cell'; export { TenantCustomerCell } from './tenant-customer-cell'; export type { TenantCustomerCellProps } from './tenant-customer-cell'; +export { TenantLicensesCell } from './tenant-licenses-cell'; +export type { TenantLicensesCellProps } from './tenant-licenses-cell'; export { TenantAccessCell } from './tenant-access-cell'; export type { TenantAccessCellProps } from './tenant-access-cell'; export { TENANT_COLUMNS, TENANTS_TABLE_COLUMNS } from './tenants-table-columns'; export type { TenantsTableColumn } from './tenants-table-columns'; -export type { TenantRow } from './tenant-row'; +export type { MultiCustomerTenantRow, TenantCustomer, TenantLicenseSummary, TenantRow } from './tenant-row'; export { accessStateTag, formatLastRead, lastReadAt, + licenseSummaryLines, providerMark, TENANT_EMPTY_VALUE, + unattributedLabel, usersCountLabel, } from './tenant-presentation'; export type { ProviderLogo, ProviderMark, + TenantLicenseLines, TenantStatusTag, TenantAccessState, TenantProvider, diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/single-customer-tenants-table-view.tsx b/openframe-frontend-core/src/components/features/cloud-tenants/single-customer-tenants-table-view.tsx new file mode 100644 index 0000000000..e25e63b437 --- /dev/null +++ b/openframe-frontend-core/src/components/features/cloud-tenants/single-customer-tenants-table-view.tsx @@ -0,0 +1,234 @@ +'use client'; + +// Lib main's tenants list, one customer per tenant: `TenantsTableView`'s default variant, the list a host renders while +// tenant-management-v2 is off. Its markup is lib main's to the class; it is deleted with that variant. + +import { useMemo } from 'react'; +import { cn } from '../../../utils/cn'; +import { openInNewTab } from '../../../utils/open-in-new-tab'; +import { ArrowRightUpIcon } from '../../icons-v2-generated/arrows/arrow-right-up-icon'; +import { Button } from '../../ui/button'; +import { type ColumnDef, DataTable, dataTableLoadingRows, type Row, useDataTable } from '../../ui/data-table'; +import { useLoadingScope } from '../../ui/loading-scope'; +import { SquareAvatar } from '../../ui/square-avatar'; +import { Tag } from '../../ui/tag'; +import { TruncateText } from '../../ui/truncate-text'; +import { TenantCell } from './tenant-cell'; +import { accessStateTag, formatLastRead, usersCountLabel } from './tenant-presentation'; +import type { TenantRow } from './tenant-row'; +import type { TenantsTableColumn } from './tenants-table-columns'; + +/** Column layout of the single-customer list (Figma 1699-8249: Tenant, Customers, Access, open). */ +const SINGLE_CUSTOMER_TENANT_COLUMNS = { + tenant: { id: 'tenant', header: 'Tenant', width: 'flex-1 min-w-0' }, + customer: { id: 'customer', header: 'Customers', width: 'w-[220px] content-lg:w-[340px]', hideAt: 'md' }, + access: { id: 'access', header: 'Access', width: 'w-[200px] content-lg:w-[216px]' }, + open: { id: 'open', width: 'w-12 shrink-0 flex-none', hideAt: 'md', align: 'right' }, +} satisfies Record; + +const getRowId = (row: TenantRow) => row.id; + +const columnMeta = ({ width, hideAt, align }: TenantsTableColumn) => ({ width, hideAt, align }); + +/** A tenant still being read: a row the table keys, every field a cell shows empty (each draws its loading form). */ +const loadingTenant = (id: string): TenantRow => ({ + id, + name: '', + provider: '', + customer: { name: '' }, + accessState: '', +}); + +/** CUSTOMERS column: customer logo + name over the synced user count. */ +function SingleCustomerTenantCustomerCell({ + name, + imageUrl, + userCount, +}: { + name: string; + imageUrl?: string | null; + userCount?: number | null; +}) { + // While the tenant is read (a loading scope) the user count is a bar too (its label is never empty). + const loading = useLoadingScope(); + return ( +
+
+ + {name} +
+ + {usersCountLabel(userCount)} + +
+ ); +} + +/** ACCESS column: the access tag over "Last read: ...". */ +function SingleCustomerTenantAccessCell({ + accessState, + lastReadAt, + now, +}: { + accessState: string; + lastReadAt?: string | null; + now?: Date; +}) { + // While the tenant is read (a loading scope) the access tag and its last read are their loading forms. + const loading = useLoadingScope(); + return ( +
+ + + {`Last read: ${formatLastRead(lastReadAt, now)}`} + +
+ ); +} + +/** The row's open-in-new-tab button: static chrome, drawn real and inert while the row is read. */ +function OpenTenantButton({ href, name }: { href: string; name: string }) { + const loading = useLoadingScope(); + return ( + // The row itself is the details link; a nested `` is invalid, so this opens the same href. +
+
+ ); +} + +export interface SingleCustomerTenantsTableViewProps { + /** The default: one customer per tenant, no licences and no funnels. */ + variant?: 'single-customer'; + rows: TenantRow[]; + /** Where a row leads: the row is a link to it, and its last cell opens it in a new tab. */ + getHref: (row: TenantRow) => string; + /** The search the rows answer; named by the "no match" message. */ + search?: string; + /** Funnels belong to the multi-customer list. */ + filters?: never; + /** The rows on screen are the previous result of a search still loading: they dim. */ + isPending?: boolean; + /** All matching tenants, loaded or not. Default: the rows given. */ + totalCount?: number; + stickyHeaderOffset?: string; + skeletonRows?: number; + hasNextPage?: boolean; + isFetchingNextPage?: boolean; + onLoadMore?: () => void; + /** The clock "Last read" is relative to. Default: the moment of the render. */ + now?: Date; +} + +/** The rows a loading tenants table draws when the host states none (a typical page of tenants). */ +const TENANTS_TABLE_SKELETON_ROWS = 20; + +/** The tenants list: tenant, customer, access state and a way into each tenant's details. */ +export function SingleCustomerTenantsTableView({ + rows, + getHref, + search = '', + isPending = false, + totalCount, + stickyHeaderOffset, + skeletonRows = TENANTS_TABLE_SKELETON_ROWS, + hasNextPage = false, + isFetchingNextPage = false, + onLoadMore, + now, +}: SingleCustomerTenantsTableViewProps) { + const columns = useMemo[]>( + () => [ + { + id: SINGLE_CUSTOMER_TENANT_COLUMNS.tenant.id, + header: SINGLE_CUSTOMER_TENANT_COLUMNS.tenant.header, + cell: ({ row }: { row: Row }) => ( + + ), + enableSorting: false, + meta: columnMeta(SINGLE_CUSTOMER_TENANT_COLUMNS.tenant), + }, + { + id: SINGLE_CUSTOMER_TENANT_COLUMNS.customer.id, + header: SINGLE_CUSTOMER_TENANT_COLUMNS.customer.header, + cell: ({ row }: { row: Row }) => ( + + ), + enableSorting: false, + meta: columnMeta(SINGLE_CUSTOMER_TENANT_COLUMNS.customer), + }, + { + id: SINGLE_CUSTOMER_TENANT_COLUMNS.access.id, + header: SINGLE_CUSTOMER_TENANT_COLUMNS.access.header, + cell: ({ row }: { row: Row }) => ( + + ), + enableSorting: false, + meta: columnMeta(SINGLE_CUSTOMER_TENANT_COLUMNS.access), + }, + { + id: SINGLE_CUSTOMER_TENANT_COLUMNS.open.id, + cell: ({ row }: { row: Row }) => ( + + ), + enableSorting: false, + meta: columnMeta(SINGLE_CUSTOMER_TENANT_COLUMNS.open), + }, + ], + [getHref, now], + ); + + // A page's loading scope: the table holds one page of placeholder rows, drawn with the real cells (`loadingCells`). + const loading = useLoadingScope(); + const loadingRows = useMemo( + () => (loading ? dataTableLoadingRows(skeletonRows, loadingTenant) : null), + [loading, skeletonRows], + ); + const table = useDataTable({ data: loadingRows ?? rows, columns, getRowId, enableSorting: false }); + + return ( + // Dim, don't unmount, the stale rows while a deferred search refetches. +
+ + } + /> + + {rows.length > 0 && onLoadMore && ( + + )} + +
+ ); +} diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-access-cell.tsx b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-access-cell.tsx index a4041cbd8f..8596e8d289 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-access-cell.tsx +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-access-cell.tsx @@ -8,20 +8,27 @@ import { accessStateTag, formatLastRead } from './tenant-presentation'; export interface TenantAccessCellProps { accessState: string; lastReadAt?: string | null; + /** A person paused the sync: said instead of the last read. */ + syncPaused?: boolean; /** The clock "Last read" is relative to. Default: the moment of the render. */ now?: Date; } -/** ACCESS column: the access tag over "Last read: ...". */ -export function TenantAccessCell({ accessState, lastReadAt, now }: TenantAccessCellProps) { +/** ACCESS column: the access tag over "Last read: ..." or "Sync paused"; a phone keeps the tag alone (Figma 3033-9343). */ +export function TenantAccessCell({ accessState, lastReadAt, syncPaused = false, now }: TenantAccessCellProps) { // While the tenant is read (a loading scope) the access tag and its last read are their loading forms. const loading = useLoadingScope(); + const line = syncPaused ? 'Sync paused' : lastReadAt ? `Last read: ${formatLastRead(lastReadAt, now)}` : null; return (
- - {`Last read: ${formatLastRead(lastReadAt, now)}`} - + {(loading || line) && ( +
+ + {line ?? ''} + +
+ )}
); } diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-customer-cell.tsx b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-customer-cell.tsx index 8817ec3e83..9a7a395b93 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-customer-cell.tsx +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-customer-cell.tsx @@ -3,27 +3,63 @@ import { useLoadingScope } from '../../ui/loading-scope'; import { SquareAvatar } from '../../ui/square-avatar'; import { TruncateText } from '../../ui/truncate-text'; -import { usersCountLabel } from './tenant-presentation'; +import { lowercaseUsersCountLabel, TENANT_EMPTY_VALUE, unattributedLabel } from './tenant-presentation'; +import type { TenantCustomer } from './tenant-row'; export interface TenantCustomerCellProps { - name: string; - /** A URL the browser can load as is. */ - imageUrl?: string | null; + /** In the host's order: the cell names the first and counts the rest. */ + customers: readonly TenantCustomer[]; userCount?: number | null; + /** Users no customer's rule claims: while there are any, the count line says how many, in the warning colour. */ + unattributedUserCount?: number | null; + /** Nothing has been read from this directory yet: the count line says so. */ + neverRead?: boolean; } -/** CUSTOMERS column: customer logo + name over the synced user count. */ -export function TenantCustomerCell({ name, imageUrl, userCount }: TenantCustomerCellProps) { +/** + * CUSTOMERS column: the first customer's logo + name and "+N" for the rest, over the synced user count — or + * "30 of 412 unattributed" while some users belong to no customer, or "Never read" before the first read. + */ +export function TenantCustomerCell({ + customers, + userCount, + unattributedUserCount, + neverRead = false, +}: TenantCustomerCellProps) { // While the tenant is read (a loading scope) the user count is a bar too (its label is never empty). const loading = useLoadingScope(); + const [first] = customers; + const more = customers.length - 1; + const unattributed = unattributedLabel(unattributedUserCount, userCount); return (
-
- - {name} -
- - {usersCountLabel(userCount)} + {first ? ( +
+ + {first.name} + {more > 0 && ( + + +{more} + {more === 1 ? ' more customer' : ' more customers'} + + )} +
+ ) : ( + {TENANT_EMPTY_VALUE} + )} + + {unattributed ?? (neverRead ? 'Never read' : lowercaseUsersCountLabel(userCount))}
); diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-licenses-cell.tsx b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-licenses-cell.tsx new file mode 100644 index 0000000000..f49e8fc685 --- /dev/null +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-licenses-cell.tsx @@ -0,0 +1,28 @@ +'use client'; + +import { cn } from '../../../utils/cn'; +import { useLoadingScope } from '../../ui/loading-scope'; +import { TruncateText } from '../../ui/truncate-text'; +import { licenseSummaryLines } from './tenant-presentation'; +import type { TenantLicenseSummary } from './tenant-row'; + +export interface TenantLicensesCellProps { + licenses?: TenantLicenseSummary | null; +} + +/** LICENCES column: assigned of purchased over what is unused (Figma 3025-3536). */ +export function TenantLicensesCell({ licenses }: TenantLicensesCellProps) { + // While the tenant is read (a loading scope) both lines are bars. + const loading = useLoadingScope(); + const { value, detail, warning } = licenseSummaryLines(licenses); + return ( +
+ {value} + {(loading || detail) && ( + + {detail ?? ''} + + )} +
+ ); +} diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.test.ts b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.test.ts new file mode 100644 index 0000000000..820c9f3da4 --- /dev/null +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.test.ts @@ -0,0 +1,56 @@ +import { describe, expect, it } from 'vitest'; +import { licenseSummaryLines, lowercaseUsersCountLabel, usersCountLabel } from './tenant-presentation'; + +describe('licenseSummaryLines', () => { + it('is the empty mark until the numbers have been read', () => { + expect(licenseSummaryLines(null)).toEqual({ value: '—', detail: null, warning: false }); + }); + + it('says the total is not available where the provider reports none', () => { + expect(licenseSummaryLines({ assigned: 88, purchased: null, unused: null })).toEqual({ + value: '88 assigned', + detail: 'Total not available', + warning: false, + }); + }); + + it('calls out what Figma 3025-3536 calls out, and leaves the rest', () => { + expect(licenseSummaryLines({ assigned: 118, purchased: 120, unused: 2 })).toEqual({ + value: '118 of 120', + detail: '2 unused', + warning: false, + }); + for (const [assigned, purchased, unused] of [ + [396, 450, 54], + [184, 225, 41], + [57, 75, 18], + ]) { + expect(licenseSummaryLines({ assigned, purchased, unused }).warning).toBe(true); + } + }); + + it('never reads a seat count below zero', () => { + expect(licenseSummaryLines({ assigned: 12, purchased: 10, unused: -2 })).toEqual({ + value: '12 of 10', + detail: '2 over', + warning: false, + }); + }); +}); + +describe('usersCountLabel', () => { + it('counts Users as the single-customer list does, and is the empty mark before the first read', () => { + expect(usersCountLabel(0)).toBe('0 Users'); + expect(usersCountLabel(1)).toBe('1 User'); + expect(usersCountLabel(227)).toBe('227 Users'); + expect(usersCountLabel(null)).toBe('—'); + }); +}); + +describe('lowercaseUsersCountLabel', () => { + it('counts users as the multi-customer list does, and is the empty mark before the first read', () => { + expect(lowercaseUsersCountLabel(1)).toBe('1 user'); + expect(lowercaseUsersCountLabel(257)).toBe('257 users'); + expect(lowercaseUsersCountLabel(null)).toBe('—'); + }); +}); diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.ts b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.ts index 4bf80f93a0..fc1cd0268d 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.ts +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-presentation.ts @@ -11,10 +11,12 @@ import type { ComponentType, SVGProps } from 'react'; import { formatRelativeTimeFrom } from '../../../utils/date-utils'; import { formatDate } from '../../../utils/format-date'; +import { presentationFor } from '../../../utils/presentation-for'; import { GoogleLogoIcon } from '../../icons-v2-generated/brand-logos/google-logo-icon'; import { Office365LogoIcon } from '../../icons-v2-generated/brand-logos/office-365-logo-icon'; import { CodingForkIcon } from '../../icons-v2-generated/coding/coding-fork-icon'; import type { TagProps } from '../../ui/tag'; +import type { TenantLicenseSummary } from './tenant-row'; /** What a cell shows when it has no value. */ export const TENANT_EMPTY_VALUE = '—'; @@ -33,10 +35,6 @@ export type TenantAccessState = /** The directory providers a tenant connects to. */ export type TenantProvider = 'MICROSOFT_365' | 'GOOGLE_WORKSPACE'; -function presentationFor(map: Record, key: string | null | undefined): V | undefined { - return key != null && key in map ? map[key as K] : undefined; -} - // Colours read off the Figma list (node 1699-8249): red for the two states that // need the customer's admin, grey for read-only, outline for write-available, // green for write-enabled. NOT_AUTHORISED has no frame of its own @@ -109,3 +107,47 @@ export function usersCountLabel(count: number | null | undefined): string { if (count == null) return TENANT_EMPTY_VALUE; return `${count} ${count === 1 ? 'User' : 'Users'}`; } + +/** The multi-customer list's count line (Figma 3025-3536): "227 users", the empty mark before the first read. */ +export function lowercaseUsersCountLabel(count: number | null | undefined): string { + if (count == null) return TENANT_EMPTY_VALUE; + return `${count} ${count === 1 ? 'user' : 'users'}`; +} + +/** + * "30 of 412 unattributed" while some synced users belong to no customer (no customer's rule claims them), or `null` + * while every user is attributed or nothing has been read. + */ +export function unattributedLabel( + unattributed: number | null | undefined, + users: number | null | undefined, +): string | null { + if (unattributed == null || unattributed <= 0) return null; + return users == null ? `${unattributed} unattributed` : `${unattributed} of ${users} unattributed`; +} + +/** The share of purchased seats left unused that the list calls out: every row of Figma 3025-3536 falls on its side. */ +const UNUSED_WARNING_SHARE = 0.1; + +export interface TenantLicenseLines { + value: string; + detail: string | null; + /** The detail is worth a look: draw it in the warning colour. */ + warning: boolean; +} + +/** + * The LICENCES cell: "118 of 120" over "2 unused"; "88 assigned" over "Total not available" where the provider reports + * no purchased seats; the empty mark until the numbers have been read. + */ +export function licenseSummaryLines(summary: TenantLicenseSummary | null | undefined): TenantLicenseLines { + if (!summary) return { value: TENANT_EMPTY_VALUE, detail: null, warning: false }; + const { assigned, purchased } = summary; + if (purchased == null) return { value: `${assigned} assigned`, detail: 'Total not available', warning: false }; + const unused = summary.unused ?? purchased - assigned; + return { + value: `${assigned} of ${purchased}`, + detail: unused < 0 ? `${-unused} over` : `${unused} unused`, + warning: unused > 0 && unused / purchased >= UNUSED_WARNING_SHARE, + }; +} diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-row.ts b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-row.ts index 769a51f34a..968f99707a 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/tenant-row.ts +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenant-row.ts @@ -1,17 +1,26 @@ -/** One connected directory tenant, as the tenants list shows it. */ -export interface TenantRow { +/** A customer a tenant's directory serves. */ +export interface TenantCustomer { + name: string; + /** A URL the browser can load as is. */ + imageUrl?: string | null; +} + +/** A directory's seats over its paid SKUs. */ +export interface TenantLicenseSummary { + assigned: number; + /** Absent when the provider does not report purchased seats (Google Workspace). */ + purchased?: number | null; + /** Purchased minus assigned; negative when the provider counts suspended seats as assigned. */ + unused?: number | null; +} + +interface TenantRowBase { id: string; /** The tenant's own name in its directory. */ name: string; /** The directory provider (`MICROSOFT_365`, `GOOGLE_WORKSPACE`); an unknown value keeps its raw name. */ provider: string; domain?: string | null; - /** The customer the tenant belongs to. */ - customer: { - name: string; - /** A URL the browser can load as is. */ - imageUrl?: string | null; - }; /** Users read from the directory; absent before the first read. */ userCount?: number | null; /** What the last access probe found (`WRITE_ENABLED`, `DISCONNECTED`, ...). */ @@ -19,3 +28,24 @@ export interface TenantRow { /** When the directory was last read; absent when it never was. */ lastReadAt?: string | null; } + +/** + * A tenant of the single-customer list, `TenantsTableView`'s default variant, which accepts no other row: a + * multi-customer host that forgets `variant` does not compile. Deleted with that variant. + */ +export interface TenantRow extends TenantRowBase { + /** The customer the tenant belongs to. */ + customer: TenantCustomer; +} + +/** A tenant of the multi-customer list (`variant="multi-customer"`): a directory serving any number of customers. */ +export interface MultiCustomerTenantRow extends TenantRowBase { + /** The customers the directory serves, in the order the host shows them; empty while it serves none. */ + customers: readonly TenantCustomer[]; + /** Of the users read, the users no customer's rule claims; absent before the first read. */ + unattributedUserCount?: number | null; + /** A person paused the sync: the row says so instead of when it was last read. */ + syncPaused?: boolean; + /** Absent until the licence numbers have been read. */ + licenses?: TenantLicenseSummary | null; +} diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-columns.ts b/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-columns.ts index be914ac559..04b47a494b 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-columns.ts +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-columns.ts @@ -9,22 +9,25 @@ export interface TenantsTableColumn { } /** - * Column layout of the tenants list (Figma 1699-8249: Tenant, Customers, - * Access, open). Data-only on purpose: the live table and the route skeleton + * Column layout of the tenants list (Figma 3025-3536: Tenant, Customers, Licences, Access, open). A tablet drops the + * licence cells and keeps the funnel (3032-4579); a phone keeps the tenant, the access tag and open (3033-9343). + * Data-only on purpose: the live table and the route skeleton * read the SAME widths, so nothing shifts when the rows arrive, and a skeleton * never imports the table's cell renderers. */ export const TENANT_COLUMNS = { tenant: { id: 'tenant', header: 'Tenant', width: 'flex-1 min-w-0' }, - customer: { id: 'customer', header: 'Customers', width: 'w-[220px] content-lg:w-[340px]', hideAt: 'md' }, - access: { id: 'access', header: 'Access', width: 'w-[200px] content-lg:w-[216px]' }, - open: { id: 'open', width: 'w-12 shrink-0 flex-none', hideAt: 'md', align: 'right' }, + customer: { id: 'customer', header: 'Customers', width: 'w-[220px] content-lg:w-[280px]', hideAt: 'md' }, + licenses: { id: 'licenses', header: 'Licences', width: 'w-[150px]', hideAt: 'lg' }, + access: { id: 'access', header: 'Access', width: 'flex-none content-md:w-[200px] content-lg:w-[216px]' }, + open: { id: 'open', width: 'w-12 shrink-0 flex-none', align: 'right' }, } satisfies Record; /** Render order of the standalone list. */ export const TENANTS_TABLE_COLUMNS: readonly TenantsTableColumn[] = [ TENANT_COLUMNS.tenant, TENANT_COLUMNS.customer, + TENANT_COLUMNS.licenses, TENANT_COLUMNS.access, TENANT_COLUMNS.open, ]; diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.test.tsx b/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.test.tsx new file mode 100644 index 0000000000..c0c9417228 --- /dev/null +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.test.tsx @@ -0,0 +1,100 @@ +import { act, render, screen } from '@testing-library/react'; +import { describe, expect, it, vi } from 'vitest'; +import type { ColumnDef, useDataTable } from '../../ui/data-table'; +import type { MultiCustomerTenantRow, TenantRow } from './tenant-row'; +import { type TenantsTableFilters, TenantsTableView } from './tenants-table-view'; + +type DataTableOptions = Parameters>[0]; + +const seen = vi.hoisted(() => ({ + columns: [] as ColumnDef[], + onColumnFiltersChange: undefined as DataTableOptions['onColumnFiltersChange'], +})); + +vi.mock('../../ui/data-table', async importOriginal => { + const actual = await importOriginal<{ useDataTable: typeof useDataTable }>(); + return { + ...actual, + useDataTable: (options: DataTableOptions) => { + seen.columns = options.columns; + seen.onColumnFiltersChange = options.onColumnFiltersChange; + return actual.useDataTable(options); + }, + }; +}); + +const ROW: MultiCustomerTenantRow = { + id: 't1', + name: 'Acme', + provider: 'MICROSOFT_365', + customers: [{ name: 'Acme' }], + accessState: 'WRITE_ENABLED', +}; + +const SINGLE_CUSTOMER_ROW: TenantRow = { + id: 't1', + name: 'Acme', + provider: 'MICROSOFT_365', + customer: { name: 'Acme' }, + userCount: 227, + accessState: 'WRITE_ENABLED', +}; + +const NO_SELECTION: TenantsTableFilters['selections'] = { tenant: [], customer: [], licenses: [], access: [] }; + +function tenantColumnFilter(filters?: TenantsTableFilters) { + render( + `/tenants/${row.id}`} filters={filters} />, + ); + return seen.columns.find(column => column.id === 'tenant')?.meta?.filter; +} + +describe('TenantsTableView, multi-customer', () => { + // Below lg only a column with `meta.filter` keeps its header; with no options the filter draws the bare label + it('declares the funnel of a column whose options came back empty', () => { + const filter = tenantColumnFilter({ options: { tenant: [] }, selections: NO_SELECTION, onChange: () => {} }); + + expect(filter).toEqual({ options: [], pending: false }); + }); + + it('draws no funnel for a column the host offers none for', () => { + expect(tenantColumnFilter()).toBeUndefined(); + }); + + it('hands the host every funnel, an untouched one empty', () => { + const onChange = vi.fn(); + tenantColumnFilter({ options: {}, selections: NO_SELECTION, onChange }); + + act(() => seen.onColumnFiltersChange?.([{ id: 'customer', value: ['c1'] }])); + + expect(onChange).toHaveBeenCalledWith({ tenant: [], customer: ['c1'], licenses: [], access: [] }); + }); +}); + +describe('TenantsTableView, single-customer (the default)', () => { + it("lays out lib main's columns: no licences, no funnels", () => { + render( `/tenants/${row.id}`} />); + + expect( + seen.columns.map(column => [column.id, column.meta?.width, column.meta?.hideAt, column.meta?.filter]), + ).toEqual([ + ['tenant', 'flex-1 min-w-0', undefined, undefined], + ['customer', 'w-[220px] content-lg:w-[340px]', 'md', undefined], + ['access', 'w-[200px] content-lg:w-[216px]', undefined, undefined], + ['open', 'w-12 shrink-0 flex-none', 'md', undefined], + ]); + }); + + it("draws lib main's cells: the capitalised count and the last read of a tenant never read", () => { + render( `/tenants/${row.id}`} />); + + expect(screen.getByText('227 Users')).toBeInTheDocument(); + expect(screen.getByText('Last read: —')).toBeInTheDocument(); + }); + + it('takes no multi-customer row, so a host that forgets the variant does not compile', () => { + // @ts-expect-error multi-customer rows need variant="multi-customer" + const forgotten = `/tenants/${row.id}`} />; + expect(forgotten.props.variant).toBeUndefined(); + }); +}); diff --git a/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.tsx b/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.tsx index e3c4373de9..71e65372d4 100644 --- a/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.tsx +++ b/openframe-frontend-core/src/components/features/cloud-tenants/tenants-table-view.tsx @@ -5,24 +5,37 @@ import { cn } from '../../../utils/cn'; import { openInNewTab } from '../../../utils/open-in-new-tab'; import { ArrowRightUpIcon } from '../../icons-v2-generated/arrows/arrow-right-up-icon'; import { Button } from '../../ui/button'; -import { type ColumnDef, DataTable, dataTableLoadingRows, type Row, useDataTable } from '../../ui/data-table'; +import { + type ColumnDef, + type ColumnFiltersState, + DataTable, + type DataTableFilterOption, + dataTableLoadingRows, + type Row, + useDataTable, +} from '../../ui/data-table'; import { useLoadingScope } from '../../ui/loading-scope'; +import { + SingleCustomerTenantsTableView, + type SingleCustomerTenantsTableViewProps, +} from './single-customer-tenants-table-view'; import { TenantAccessCell } from './tenant-access-cell'; import { TenantCell } from './tenant-cell'; import { TenantCustomerCell } from './tenant-customer-cell'; -import type { TenantRow } from './tenant-row'; +import { TenantLicensesCell } from './tenant-licenses-cell'; +import type { MultiCustomerTenantRow } from './tenant-row'; import { TENANT_COLUMNS, type TenantsTableColumn } from './tenants-table-columns'; -const getRowId = (row: TenantRow) => row.id; +const getRowId = (row: MultiCustomerTenantRow) => row.id; const columnMeta = ({ width, hideAt, align }: TenantsTableColumn) => ({ width, hideAt, align }); /** A tenant still being read: a row the table keys, every field a cell shows empty (each draws its loading form). */ -const loadingTenant = (id: string): TenantRow => ({ +const loadingTenant = (id: string): MultiCustomerTenantRow => ({ id, name: '', provider: '', - customer: { name: '' }, + customers: [{ name: '' }], accessState: '', }); @@ -45,16 +58,35 @@ function OpenTenantButton({ href, name }: { href: string; name: string }) { ); } +/** The columns whose header carries a funnel (Figma 3036-4860). */ +export const TENANTS_TABLE_FILTER_COLUMNS = ['tenant', 'customer', 'licenses', 'access'] as const; + +export type TenantsTableFilterColumn = (typeof TENANTS_TABLE_FILTER_COLUMNS)[number]; + +/** Each column's funnel: what it offers, what is ticked. The host narrows the rows; the view only draws. */ +export interface TenantsTableFilters { + /** A column the host leaves out has no funnel; one with no options draws its bare label. */ + options: Partial>; + selections: Readonly>; + onChange: (next: Record) => void; + /** The options are in flight: the funnels draw, inert. */ + pending?: boolean; +} + /** * Click handler that opens `href` in a new tab. The row is itself the details * link and an `
` cannot be nested in an ``, so the button opens it by script. */ -export interface TenantsTableViewProps { - rows: TenantRow[]; +interface MultiCustomerTenantsTableViewProps { + /** A directory per row that serves any number of customers, with its licences and the column funnels. */ + variant: 'multi-customer'; + rows: MultiCustomerTenantRow[]; /** Where a row leads: the row is a link to it, and its last cell opens it in a new tab. */ - getHref: (row: TenantRow) => string; + getHref: (row: MultiCustomerTenantRow) => string; /** The search the rows answer; named by the "no match" message. */ search?: string; + /** The funnels of the column headers. Absent: none, as on the product page. */ + filters?: TenantsTableFilters; /** The rows on screen are the previous result of a search still loading: they dim. */ isPending?: boolean; /** All matching tenants, loaded or not. Default: the rows given. */ @@ -68,14 +100,27 @@ export interface TenantsTableViewProps { now?: Date; } +/** The single-customer list unless `variant` is 'multi-customer', the one that takes funnels and needs its own rows. */ +export type TenantsTableViewProps = SingleCustomerTenantsTableViewProps | MultiCustomerTenantsTableViewProps; + +/** The tenants list, in the layout its `variant` names. */ +export function TenantsTableView(props: TenantsTableViewProps) { + return props.variant === 'multi-customer' ? ( + + ) : ( + + ); +} + /** The rows a loading tenants table draws when the host states none (a typical page of tenants). */ const TENANTS_TABLE_SKELETON_ROWS = 20; -/** The tenants list: tenant, customer, access state and a way into each tenant's details. */ -export function TenantsTableView({ +/** The tenants list: tenant, customers, licences, access state and a way into each tenant's details. */ +function MultiCustomerTenantsTableView({ rows, getHref, search = '', + filters, isPending = false, totalCount, stickyHeaderOffset, @@ -84,51 +129,75 @@ export function TenantsTableView({ isFetchingNextPage = false, onLoadMore, now, -}: TenantsTableViewProps) { - const columns = useMemo[]>( - () => [ +}: MultiCustomerTenantsTableViewProps) { + const filterOptions = filters?.options; + const filtersPending = filters?.pending ?? false; + const columns = useMemo[]>(() => { + /** + * A column's funnel, while the host offers one. Declared with no options too: below lg only a filtered column keeps + * its header, and the column filter draws the bare label when there is nothing to choose. + */ + const funnel = (id: TenantsTableFilterColumn) => { + const options = filterOptions?.[id]; + return options ? { filter: { options, pending: filtersPending } } : {}; + }; + return [ { id: TENANT_COLUMNS.tenant.id, header: TENANT_COLUMNS.tenant.header, - cell: ({ row }: { row: Row }) => ( + cell: ({ row }: { row: Row }) => ( ), enableSorting: false, - meta: columnMeta(TENANT_COLUMNS.tenant), + meta: { ...columnMeta(TENANT_COLUMNS.tenant), ...funnel('tenant') }, }, { id: TENANT_COLUMNS.customer.id, header: TENANT_COLUMNS.customer.header, - cell: ({ row }: { row: Row }) => ( + cell: ({ row }: { row: Row }) => ( ), enableSorting: false, - meta: columnMeta(TENANT_COLUMNS.customer), + meta: { ...columnMeta(TENANT_COLUMNS.customer), ...funnel('customer') }, + }, + { + id: TENANT_COLUMNS.licenses.id, + header: TENANT_COLUMNS.licenses.header, + cell: ({ row }: { row: Row }) => ( + + ), + enableSorting: false, + meta: { ...columnMeta(TENANT_COLUMNS.licenses), ...funnel('licenses') }, }, { id: TENANT_COLUMNS.access.id, header: TENANT_COLUMNS.access.header, - cell: ({ row }: { row: Row }) => ( - + cell: ({ row }: { row: Row }) => ( + ), enableSorting: false, - meta: columnMeta(TENANT_COLUMNS.access), + meta: { ...columnMeta(TENANT_COLUMNS.access), ...funnel('access') }, }, { id: TENANT_COLUMNS.open.id, - cell: ({ row }: { row: Row }) => ( + cell: ({ row }: { row: Row }) => ( ), enableSorting: false, meta: columnMeta(TENANT_COLUMNS.open), }, - ], - [getHref, now], - ); + ]; + }, [getHref, now, filterOptions, filtersPending]); // A page's loading scope: the table holds one page of placeholder rows, drawn with the real cells (`loadingCells`). const loading = useLoadingScope(); @@ -136,7 +205,31 @@ export function TenantsTableView({ () => (loading ? dataTableLoadingRows(skeletonRows, loadingTenant) : null), [loading, skeletonRows], ); - const table = useDataTable({ data: loadingRows ?? rows, columns, getRowId, enableSorting: false }); + const selections = filters?.selections; + const onFiltersChange = filters?.onChange; + const columnFilters = useMemo( + () => + TENANTS_TABLE_FILTER_COLUMNS.flatMap(id => + selections && selections[id].length > 0 ? [{ id, value: selections[id] }] : [], + ), + [selections], + ); + const table = useDataTable({ + data: loadingRows ?? rows, + columns, + getRowId, + enableSorting: false, + state: { columnFilters }, + onColumnFiltersChange: updater => { + const next = typeof updater === 'function' ? updater(columnFilters) : updater; + const picked = (id: TenantsTableFilterColumn) => { + const value = next.find(filter => filter.id === id)?.value; + return Array.isArray(value) ? (value as string[]) : []; + }; + const selected = Object.fromEntries(TENANTS_TABLE_FILTER_COLUMNS.map(id => [id, picked(id)])); + onFiltersChange?.(selected as Record); + }, + }); return ( // Dim, don't unmount, the stale rows while a deferred search refetches. @@ -152,7 +245,9 @@ export function TenantsTableView({ skeletonRows={skeletonRows} emptyState={{ title: 'No tenants match', - description: `Nothing matches "${search}". Try a different name, domain or customer.`, + description: search + ? `Nothing matches "${search}". Try a different name, domain or customer.` + : 'Nothing matches the selected filters. Try adjusting them.', }} rowClassName="mb-[var(--spacing-system-xxs)]" rowHref={getHref} diff --git a/openframe-frontend-core/src/components/features/devices/device-directory.test.ts b/openframe-frontend-core/src/components/features/devices/device-directory.test.ts new file mode 100644 index 0000000000..41eadf3768 --- /dev/null +++ b/openframe-frontend-core/src/components/features/devices/device-directory.test.ts @@ -0,0 +1,42 @@ +import { describe, expect, it } from 'vitest'; +import { directorySourceLabel, directoryUserLines, directoryUserLinkLabel } from './device-directory'; + +describe('directoryUserLines', () => { + it('names the primary user', () => { + expect(directoryUserLines({ directoryUserLink: 'PRIMARY', directoryUserName: 'Olivia Grant' })).toEqual({ + name: 'Olivia Grant', + detail: 'Primary user', + }); + }); + + it('counts the users of a shared device, singular for one', () => { + expect(directoryUserLines({ directoryUserLink: 'SHARED', directoryUserCount: 2 })).toEqual({ + name: 'Shared', + detail: '2 recent users', + }); + expect(directoryUserLines({ directoryUserLink: 'SHARED', directoryUserCount: 1 }).detail).toBe('1 recent user'); + }); + + it('draws the empty mark when nobody is tied, or nothing is known', () => { + expect(directoryUserLines({ directoryUserLink: 'NONE' })).toEqual({ name: '—', detail: null }); + expect(directoryUserLines({})).toEqual({ name: '—', detail: null }); + }); +}); + +describe('labels', () => { + it("uses Figma's words", () => { + expect(directoryUserLinkLabel('NONE')).toBe('No user'); + expect(directorySourceLabel('MICROSOFT_365')).toBe('M365'); + expect(directorySourceLabel('GOOGLE_WORKSPACE')).toBe('GOOGLE'); + }); + + it('keeps a value this build does not know', () => { + expect(directoryUserLinkLabel('NEW')).toBe('NEW'); + expect(directorySourceLabel('NEW')).toBe('NEW'); + }); + + it('keeps a value named like an inherited key', () => { + expect(directoryUserLinkLabel('toString')).toBe('toString'); + expect(directorySourceLabel('constructor')).toBe('constructor'); + }); +}); diff --git a/openframe-frontend-core/src/components/features/devices/device-directory.ts b/openframe-frontend-core/src/components/features/devices/device-directory.ts new file mode 100644 index 0000000000..746666a3e5 --- /dev/null +++ b/openframe-frontend-core/src/components/features/devices/device-directory.ts @@ -0,0 +1,55 @@ +import { presentationFor } from '../../../utils/presentation-for'; +import type { DeviceRow } from './types'; + +/** The schema's `DirectoryUserLink`: who a device is tied to in a directory. */ +export type DeviceDirectoryUserLink = 'PRIMARY' | 'SHARED' | 'NONE'; + +/** The schema's `DirectorySource`: a directory that knows a device. */ +export type DeviceDirectorySource = 'MICROSOFT_365' | 'GOOGLE_WORKSPACE'; + +const USER_LINK_LABELS = { + PRIMARY: 'Primary user', + SHARED: 'Shared', + NONE: 'No user', +} satisfies Record; + +const SOURCE_LABELS = { + MICROSOFT_365: 'M365', + GOOGLE_WORKSPACE: 'GOOGLE', +} satisfies Record; + +/** The USER funnel's option (Figma 1136:64807). A value this build does not know keeps its own name. */ +export function directoryUserLinkLabel(link: string): string { + return presentationFor(USER_LINK_LABELS, link) ?? link; +} + +/** The SOURCES tag: which directory knows the device. */ +export function directorySourceLabel(source: string): string { + return presentationFor(SOURCE_LABELS, source) ?? source; +} + +const EMPTY_USER = '—'; + +// The row carries the wire's string: a member compared to it is typed here, so a misspelt one fails to compile. +const PRIMARY_LINK: DeviceDirectoryUserLink = 'PRIMARY'; +const SHARED_LINK: DeviceDirectoryUserLink = 'SHARED'; + +/** + * The USER cell's two lines (Figma 865:55733): the primary user over "Primary user", "Shared" over how many, or the + * empty mark when nobody is tied to the device. + */ +export function directoryUserLines( + device: Pick, +): { + name: string; + detail: string | null; +} { + if (device.directoryUserLink === PRIMARY_LINK) { + return { name: device.directoryUserName ?? EMPTY_USER, detail: USER_LINK_LABELS.PRIMARY }; + } + if (device.directoryUserLink === SHARED_LINK) { + const count = device.directoryUserCount ?? 0; + return { name: USER_LINK_LABELS.SHARED, detail: `${count} recent ${count === 1 ? 'user' : 'users'}` }; + } + return { name: EMPTY_USER, detail: null }; +} diff --git a/openframe-frontend-core/src/components/features/devices/devices-filter-toolbar.tsx b/openframe-frontend-core/src/components/features/devices/devices-filter-toolbar.tsx index 080783e5a7..0a13c07637 100644 --- a/openframe-frontend-core/src/components/features/devices/devices-filter-toolbar.tsx +++ b/openframe-frontend-core/src/components/features/devices/devices-filter-toolbar.tsx @@ -29,6 +29,8 @@ export interface DevicesFilterToolbarProps { selectedTags: FilterModalProps['selectedTags']; onTagsChange: FilterModalProps['onTagsChange']; isLoading?: boolean; + /** The search field's prompt. Default "Search for Devices". */ + searchPlaceholder?: string; /** * When true (default), pins the toolbar at the top with the same negative-margin @@ -67,6 +69,7 @@ export function DevicesFilterToolbar({ selectedTags, onTagsChange, isLoading, + searchPlaceholder = 'Search for Devices', sticky = true, toolbarRef, }: DevicesFilterToolbarProps) { @@ -87,7 +90,7 @@ export function DevicesFilterToolbar({ onSearchChange={onSearchChange} onTagRemove={onTagRemove} onClearAll={onClearAll} - placeholder="Search for Devices" + placeholder={searchPlaceholder} addMorePlaceholder="Add More..." /> diff --git a/openframe-frontend-core/src/components/features/devices/devices-panel-view.tsx b/openframe-frontend-core/src/components/features/devices/devices-panel-view.tsx index 8a915c305b..e4a346d442 100644 --- a/openframe-frontend-core/src/components/features/devices/devices-panel-view.tsx +++ b/openframe-frontend-core/src/components/features/devices/devices-panel-view.tsx @@ -99,6 +99,8 @@ export interface DevicesPanelViewProps { hideColumns?: string[]; /** Filter keys to drop from the funnels and the grid row; the column itself stays. */ hideFilters?: string[]; + /** Adds the USER and SOURCES columns and funnels, for a tenant with directories. Default: neither. */ + directoryColumns?: boolean; /** Message shown when the list is empty. */ emptyMessage?: string; /** Drawn instead of the toolbar and the list: the pristine, genuinely empty panel. */ @@ -151,6 +153,7 @@ export function DevicesPanelView({ actionsColumn, hideColumns, hideFilters, + directoryColumns = false, emptyMessage = 'No devices found. Try adjusting your search or filters.', emptyState, noOrganizations = false, @@ -164,11 +167,17 @@ export function DevicesPanelView({ const scoped = useLoadingScope(); const loading = scoped || loadingGiven; const gridColumns = - filterColumns ?? getDeviceFilterColumns(deviceFilters).filter(column => !hideFilters?.includes(column.key)); + filterColumns ?? + getDeviceFilterColumns(deviceFilters, { directoryColumns }).filter(column => !hideFilters?.includes(column.key)); const list = ( <> - + {viewMode === 'table' ? ( ({ onColumnFiltersChange={onColumnFiltersChange} actionsColumn={actionsColumn} hideColumns={hideColumns} + directoryColumns={directoryColumns} disableColumnFilters={hideFilters} totalCount={loading ? undefined : totalCount} footerSlot={ diff --git a/openframe-frontend-core/src/components/features/devices/devices-table-columns.tsx b/openframe-frontend-core/src/components/features/devices/devices-table-columns.tsx index 45e84e49e3..0cf5fbdd18 100644 --- a/openframe-frontend-core/src/components/features/devices/devices-table-columns.tsx +++ b/openframe-frontend-core/src/components/features/devices/devices-table-columns.tsx @@ -23,6 +23,7 @@ import { } from '../../ui'; import { DATA_TABLE_SKELETON_ROWS } from '../../ui/data-table/utils'; import { OSTypeBadge } from '../os-type-badge'; +import { directorySourceLabel, directoryUserLines, directoryUserLinkLabel } from './device-directory'; import { getDeviceName } from './device-name'; import { getDeviceStatusConfig } from './device-status'; import { DEFAULT_VISIBLE_STATUSES } from './device-statuses'; @@ -129,6 +130,8 @@ export interface DevicesTableBodyProps { actionsColumn?: ColumnDef; /** Column ids to drop from the base table columns (e.g. ['organization'] when scoped to a single org). */ hideColumns?: string[]; + /** Adds the USER and SOURCES columns, for a host whose tenant has directories. Default: neither. */ + directoryColumns?: boolean; /** Column ids whose header filter is dropped while the column stays visible (e.g. ['status'] on the archive page). */ disableColumnFilters?: string[]; /** The facet query is still in flight, see `getDeviceTableColumns`. */ @@ -168,6 +171,7 @@ export function DevicesTableBody({ onColumnFiltersChange, actionsColumn, hideColumns, + directoryColumns = false, disableColumnFilters, filtersPending, totalCount, @@ -177,12 +181,16 @@ export function DevicesTableBody({ const columns = useMemo[]>(() => { const hidden = new Set(hideColumns ?? []); const unfiltered = new Set(disableColumnFilters ?? []); - const base = getDeviceTableColumns(deviceFilters ?? null, filtersPending) + const base = getDeviceTableColumns(deviceFilters ?? null, filtersPending, { + directoryColumns, + // Without the customer column there is room for the sources from where the customer's column would have started. + roomyDirectory: hidden.has('organization'), + }) .filter(c => !c.id || !hidden.has(c.id)) .map(c => (c.id && unfiltered.has(c.id) ? { ...c, meta: { ...c.meta, filter: undefined } } : c)); const open = getDeviceOpenColumn(); return actionsColumn ? [...base, actionsColumn, open] : [...base, open]; - }, [deviceFilters, filtersPending, actionsColumn, hideColumns, disableColumnFilters]); + }, [deviceFilters, filtersPending, actionsColumn, hideColumns, directoryColumns, disableColumnFilters]); // While loading the table holds one page of empty rows, drawn with the real cells: every part of a row draws its // own loading form (`DataTable.Body`'s `loadingCells`), so a loading row is the loaded row's own layout. @@ -257,11 +265,43 @@ function DeviceLastSeen({ lastSeen }: { lastSeen: string | undefined }) { ); } +/** The name over its role, as the USER column reads it (Figma 865:55733); the empty mark when nobody is tied. */ +function DirectoryUserCell({ device }: { device: DeviceRow }) { + const loading = useLoadingScope(); + if (loading && !device.directoryUserLink) { + return ; + } + const { name, detail } = directoryUserLines(device); + return ( +
+ {name} + {detail && ( + + {detail} + + )} +
+ ); +} + +/** The directories that know the device, as tags (Figma 187:61663); nothing when none does. */ +function DirectorySourcesCell({ sources }: { sources: readonly string[] | undefined }) { + return ( +
+ {(sources ?? []).map(source => ( + + ))} +
+ ); +} + export interface DeviceFilterColumn { key: string; label: string; filterable?: boolean; filterOptions?: DeviceFilterOption[]; + /** Filters in the filter window from `lg` until `xl` too: its column's header has no funnel there. */ + inWindowLgToXl?: boolean; } /** A device filter dropdown entry: `meta.filter.options` plus the facet count. */ @@ -277,6 +317,8 @@ function buildDeviceFilterOptions(deviceFilters?: DeviceFilters | null): { status: DeviceFilterOption[]; os: DeviceFilterOption[]; organization: DeviceFilterOption[]; + user: DeviceFilterOption[]; + sources: DeviceFilterOption[]; } { // Show only DEFAULT_VISIBLE_STATUSES (DELETED and legacy ARCHIVED live on /devices/archive) const status = (deviceFilters?.statuses ?? []) @@ -294,19 +336,56 @@ function buildDeviceFilterOptions(deviceFilters?: DeviceFilters | null): { })), ); - return { status, os, organization }; + const user = (deviceFilters?.userLinks ?? []).map(link => ({ + id: link.value, + label: directoryUserLinkLabel(link.value), + value: link.value, + count: link.count, + })); + + const sources = (deviceFilters?.directorySources ?? []).map(source => ({ + id: source.value, + label: directorySourceLabel(source.value), + value: source.value, + count: source.count, + })); + + return { status, os, organization, user, sources }; +} + +/** The directory columns of a device list: the table and its filter window take the same ones. */ +interface DeviceDirectoryColumnOptions { + directoryColumns?: boolean; + roomyDirectory?: boolean; } // Filter column metadata used by the external filter modal (useTagFilterModal). // Kept separate from the table ColumnDef because DataTable doesn't carry the // filter metadata that the external mobile filter modal needs. -export function getDeviceFilterColumns(deviceFilters?: DeviceFilters | null): DeviceFilterColumn[] { +// `roomyDirectory` is the table's own (`getDeviceTableColumns`): beside the customer column SOURCES shows only from +// `xl`, and the header has no funnel for it from `lg` until then, so the window carries it there. +export function getDeviceFilterColumns( + deviceFilters?: DeviceFilters | null, + { directoryColumns = false, roomyDirectory = false }: DeviceDirectoryColumnOptions = {}, +): DeviceFilterColumn[] { const options = buildDeviceFilterOptions(deviceFilters); return [ { key: 'device', label: 'DEVICE', }, + ...(directoryColumns + ? [ + { key: 'user', label: 'USER', filterable: true, filterOptions: options.user }, + { + key: 'sources', + label: 'SOURCES', + filterable: true, + filterOptions: options.sources, + inWindowLgToXl: !roomyDirectory, + }, + ] + : []), { key: 'status', label: 'STATUS', filterable: true, filterOptions: options.status }, { key: 'os', label: 'OS', filterable: true, filterOptions: options.os }, { key: 'organization', label: 'CUSTOMER', filterable: true, filterOptions: options.organization }, @@ -318,17 +397,51 @@ export function getDeviceFilterColumns(deviceFilters?: DeviceFilters | null): De * funnels drawn (inert) rather than growing them when it answers. Absent means * these are the final options: an empty one then hides its funnel, which is what * a list with no facet source of its own wants. + * @param options.directoryColumns Adds USER and SOURCES after DEVICE. Off by default: a picker or a tenant with no + * directories has neither. + * @param options.roomyDirectory No customer column beside them (one customer's list), so SOURCES shows from `lg` + * rather than `xl`. */ export function getDeviceTableColumns( deviceFilters?: DeviceFilters | null, filtersPending?: boolean, + { directoryColumns = false, roomyDirectory = false }: DeviceDirectoryColumnOptions = {}, ): ColumnDef[] { const { status: statusFilterOptions, os: osFilterOptions, organization: orgFilterOptions, + user: userFilterOptions, + sources: sourcesFilterOptions, } = buildDeviceFilterOptions(deviceFilters); + const directory: ColumnDef[] = directoryColumns + ? [ + { + id: 'user', + header: 'USER', + cell: ({ row }: { row: Row }) => , + enableSorting: false, + meta: { + width: 'min-w-0 content-lg:w-[15%]', + hideAt: 'lg', + filter: { options: userFilterOptions, pending: filtersPending }, + }, + }, + { + id: 'sources', + header: 'SOURCES', + cell: ({ row }: { row: Row }) => , + enableSorting: false, + meta: { + width: 'min-w-0 content-lg:w-[11%]', + hideAt: roomyDirectory ? 'lg' : 'xl', + filter: { options: sourcesFilterOptions, pending: filtersPending }, + }, + }, + ] + : []; + return [ { accessorKey: 'device', @@ -347,8 +460,10 @@ export function getDeviceTableColumns( ); }, - meta: { width: 'flex-1 content-md:w-1/4' }, + // The name takes what the other columns leave: with two more of them, their shares below shrink to leave some. + meta: { width: directoryColumns ? 'flex-1 min-w-0' : 'flex-1 content-md:w-1/4' }, }, + ...directory, { accessorKey: 'status', id: 'status', @@ -366,7 +481,7 @@ export function getDeviceTableColumns( ); }, meta: { - width: 'w-auto shrink-0 content-md:w-1/5', + width: directoryColumns ? 'w-auto shrink-0 content-md:w-[14%]' : 'w-auto shrink-0 content-md:w-1/5', // Declared unconditionally, empty options and all. `meta.filter` is what // keeps a header cell visible below `lg`, so dropping it until the // options query resolves made every header on a tablet disappear on @@ -383,7 +498,7 @@ export function getDeviceTableColumns( ), meta: { - width: 'w-[200px] content-md:w-1/6', + width: directoryColumns ? 'w-[200px] content-md:w-[10%]' : 'w-[200px] content-md:w-1/6', hideAt: 'md', filter: { options: osFilterOptions, pending: filtersPending }, }, @@ -394,7 +509,7 @@ export function getDeviceTableColumns( header: 'CUSTOMER', cell: ({ row }: { row: Row }) => , meta: { - width: 'w-1/6', + width: directoryColumns ? 'w-[14%]' : 'w-1/6', hideAt: 'lg', filter: { options: orgFilterOptions, placement: 'bottom-end', pending: filtersPending }, }, diff --git a/openframe-frontend-core/src/components/features/devices/index.ts b/openframe-frontend-core/src/components/features/devices/index.ts index 9ff90e0fc1..e03104d530 100644 --- a/openframe-frontend-core/src/components/features/devices/index.ts +++ b/openframe-frontend-core/src/components/features/devices/index.ts @@ -1,5 +1,12 @@ 'use client'; +export { + type DeviceDirectorySource, + type DeviceDirectoryUserLink, + directorySourceLabel, + directoryUserLines, + directoryUserLinkLabel, +} from './device-directory'; export { formatLastOnline } from './device-last-online'; export { type DeviceNameSource, getDeviceName, matchesDeviceName } from './device-name'; export { diff --git a/openframe-frontend-core/src/components/features/devices/types.ts b/openframe-frontend-core/src/components/features/devices/types.ts index deabcfc2f8..3b20254336 100644 --- a/openframe-frontend-core/src/components/features/devices/types.ts +++ b/openframe-frontend-core/src/components/features/devices/types.ts @@ -34,6 +34,14 @@ export interface DeviceRow extends DeviceNameSource { organizationImageUrl?: string | null; organizationImageHash?: string | null; tags?: DeviceTag[]; + /** Who the device is tied to in a directory: PRIMARY, SHARED or NONE. The USER column reads it. */ + directoryUserLink?: string; + /** The primary user's name; only PRIMARY has one. */ + directoryUserName?: string | null; + /** How many users are tied to it: "N recent users" when SHARED. */ + directoryUserCount?: number; + /** The directories that know the device besides the agent. The SOURCES column reads it. */ + directorySources?: readonly string[]; /** The viewer's unread notifications about this device. Absent or 0: no indicator. */ unreadNotificationCount?: number; } @@ -63,6 +71,10 @@ export interface DeviceFilters { organizationIds: DeviceFilterTag[]; tagKeys: TagFilterOption[]; filteredCount: number; + /** Behind the USER funnel; only hosts that draw the directory columns read it. */ + userLinks?: DeviceFilterValue[]; + /** Behind the SOURCES funnel; only hosts that draw the directory columns read it. */ + directorySources?: DeviceFilterValue[]; } /** What narrows a device list, in the backend's field names. */ @@ -73,4 +85,6 @@ export interface DeviceFilterInput { organizationIds?: string[]; tagKeys?: string[]; tagValues?: string[]; + userLinks?: string[]; + directorySources?: string[]; } diff --git a/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.test.ts b/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.test.ts new file mode 100644 index 0000000000..1eb200f776 --- /dev/null +++ b/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.test.ts @@ -0,0 +1,90 @@ +import { act, renderHook } from '@testing-library/react'; +import { createElement, type ReactNode } from 'react'; +import { afterEach, describe, expect, it, vi } from 'vitest'; +import { ContentAreaWidthContext } from '../../../hooks/ui/use-content-breakpoint'; +import { getDeviceFilterColumns } from './devices-table-columns'; +import { useTagFilterModal } from './use-tag-filter-modal'; + +/** Applies the modal the way FilterModal does: the column filters first, then the tags. */ +function apply(columns: ReturnType, columnFilters: Record) { + const setParams = vi.fn(); + const { result } = renderHook(() => + useTagFilterModal({ tags: [], deviceFilters: null, columns, setParams, onApplied: () => {} }), + ); + act(() => { + result.current.handleFilterChange(columnFilters); + result.current.handleTagsChange([]); + }); + return setParams.mock.calls[0][0] as Record; +} + +describe('useTagFilterModal', () => { + const directoryColumns = getDeviceFilterColumns(null, { directoryColumns: true }); + + it('sends the ticked USER and SOURCES options', () => { + const params = apply(directoryColumns, { user: ['PRIMARY'], sources: ['MICROSOFT_365'] }); + + expect(params.userLinks).toEqual(['PRIMARY']); + expect(params.directorySources).toEqual(['MICROSOFT_365']); + }); + + // FilterModal drops a group whose last option was unticked, and Reset sends no group at all + it('clears USER and SOURCES when no option of theirs is ticked', () => { + const params = apply(directoryColumns, { status: ['ONLINE'] }); + + expect(params.userLinks).toEqual([]); + expect(params.directorySources).toEqual([]); + }); + + it('leaves the directory params out for a host without the directory columns', () => { + const params = apply(getDeviceFilterColumns(null), {}); + + expect(params).not.toHaveProperty('userLinks'); + expect(params).not.toHaveProperty('directorySources'); + }); +}); + +/** The filter window's groups, for a host laid out in a content area this wide. */ +function groupIds(columns: ReturnType, contentWidth: number) { + const { result } = renderHook( + () => useTagFilterModal({ tags: [], deviceFilters: null, columns, setParams: vi.fn(), onApplied: () => {} }), + { + wrapper: ({ children }: { children: ReactNode }) => + createElement(ContentAreaWidthContext.Provider, { value: contentWidth }, children), + }, + ); + return result.current.filterGroups.map(group => group.id); +} + +describe('useTagFilterModal filter groups', () => { + const directoryColumns = getDeviceFilterColumns(null, { directoryColumns: true }); + + afterEach(() => { + vi.restoreAllMocks(); + }); + + it('follows the content area: a docked panel narrowing it under a wide window brings every group back', () => { + const narrowWindow = window.matchMedia; + vi.spyOn(window, 'matchMedia').mockImplementation(query => ({ ...narrowWindow(query), matches: true })); + + expect(groupIds(directoryColumns, 600)).toEqual(['user', 'sources', 'status', 'os', 'organization']); + }); + + it('leaves a tablet-width area to the header funnels', () => { + expect(groupIds(directoryColumns, 800)).toEqual([]); + }); + + it('carries SOURCES from lg until xl, where beside the customer column its header has no funnel', () => { + expect(groupIds(directoryColumns, 1100)).toEqual(['sources']); + }); + + it('leaves SOURCES to the header from xl, where its funnel is back', () => { + expect(groupIds(directoryColumns, 1300)).toEqual([]); + }); + + it("leaves SOURCES to the header on one customer's list", () => { + const columns = getDeviceFilterColumns(null, { directoryColumns: true, roomyDirectory: true }); + + expect(groupIds(columns, 1100)).toEqual([]); + }); +}); diff --git a/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.ts b/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.ts index 186b649dba..58fd78e6b4 100644 --- a/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.ts +++ b/openframe-frontend-core/src/components/features/devices/use-tag-filter-modal.ts @@ -1,7 +1,7 @@ 'use client'; import { useCallback, useMemo, useRef, useState } from 'react'; -import { useMdUp } from '../../../hooks/ui/use-media-query'; +import { useContentLgUp, useContentMdUp, useContentXlUp } from '../../../hooks/ui/use-content-breakpoint'; import type { DeviceFilters } from './types'; function isCompleteTag(tag: string): boolean { @@ -19,7 +19,13 @@ interface FilterOption { interface UseTagFilterModalParams { tags: string[]; deviceFilters: DeviceFilters | null; - columns: Array<{ key: string; label: string; filterable?: boolean; filterOptions?: FilterOption[] }>; + columns: Array<{ + key: string; + label: string; + filterable?: boolean; + filterOptions?: FilterOption[]; + inWindowLgToXl?: boolean; + }>; /** `useApiParams`' setter, each device list param is a list of ids. */ setParams: (params: Record) => void; /** @@ -39,7 +45,11 @@ export function useTagFilterModal({ setParams, onApplied = scrollMainToTop, }: UseTagFilterModalParams) { - const isMdUp = useMdUp(); + // The content area's step, not the window's: the table header follows it, and a docked side panel narrows it while + // the window stays wide. + const isMdUp = useContentMdUp(); + const lgUp = useContentLgUp(); + const xlUp = useContentXlUp(); const [isOpen, setIsOpen] = useState(false); // FilterModal calls onFilterChange first, then onTagsChange. @@ -49,16 +59,19 @@ export function useTagFilterModal({ const open = useCallback(() => setIsOpen(true), []); const close = useCallback(() => setIsOpen(false), []); - const filterGroups = useMemo(() => { - if (isMdUp) return []; - return columns - .filter(column => column.filterable) - .map(column => ({ - id: column.key, - title: column.label, - options: column.filterOptions || [], - })); - }, [columns, isMdUp]); + // Below md the table draws no header, so every column filters here; from lg until xl only the columns whose header + // has no funnel there do. + const filterGroups = useMemo( + () => + columns + .filter(column => column.filterable && (!isMdUp || (lgUp && xlUp === false && column.inWindowLgToXl))) + .map(column => ({ + id: column.key, + title: column.label, + options: column.filterOptions || [], + })), + [columns, isMdUp, lgUp, xlUp], + ); const tagFilterKeys = useMemo(() => { if (!deviceFilters?.tagKeys) return []; @@ -79,6 +92,9 @@ export function useTagFilterModal({ pendingFiltersRef.current = columnFilters; }, []); + // Only a host that draws the directory columns has the USER and SOURCES groups: another's list params stay untouched + const hasDirectoryGroups = useMemo(() => columns.some(column => column.key === 'user'), [columns]); + // Step 2: combine with buffered filters and flush (called second by FilterModal) const handleTagsChange = useCallback( (newTags: string[]) => { @@ -87,12 +103,14 @@ export function useTagFilterModal({ statuses: cf.status || [], osTypes: cf.os || [], organizationIds: cf.organization || [], + // FilterModal drops a group with nothing ticked, so a missing group clears its param + ...(hasDirectoryGroups && { userLinks: cf.user || [], directorySources: cf.sources || [] }), tags: newTags.filter(isCompleteTag), }); pendingFiltersRef.current = {}; onApplied(); }, - [setParams, onApplied], + [setParams, onApplied, hasDirectoryGroups], ); return { diff --git a/openframe-frontend-core/src/components/navigation/app-layout.tsx b/openframe-frontend-core/src/components/navigation/app-layout.tsx index 030e90dc17..a031ab9f41 100644 --- a/openframe-frontend-core/src/components/navigation/app-layout.tsx +++ b/openframe-frontend-core/src/components/navigation/app-layout.tsx @@ -2,7 +2,7 @@ import { useCallback, useEffect, useMemo, useRef, useState } from 'react'; import type { CSSProperties, ReactNode } from 'react'; -import { ContentAreaWidthContext, contentBreakpointFor } from '../../hooks/ui/use-content-breakpoint'; +import { ContentAreaWidthContext, contentStepFor } from '../../hooks/ui/use-content-breakpoint'; import { useIsomorphicLayoutEffect } from '../../hooks/ui/use-isomorphic-layout-effect'; import type { NavigationSidebarConfig } from '../../types/navigation'; import { cn } from '../../utils'; @@ -203,14 +203,14 @@ export function AppLayout({ useIsomorphicLayoutEffect(() => { if (!adaptive || !mainElement) return undefined; - // Every reader asks for the breakpoint (`useContentBreakpoint`), so only a - // crossing re-renders the layout: kept at the old width, the state bails out. + // Every reader asks for a step (`useContentBreakpoint`, `useContentXlUp`), so + // only a crossing re-renders the layout: kept at the old width, the state bails out. // Per pixel, the uncompiled layout and every breakpoint consumer re-rendered on // each frame of a sidebar toggle, a window drag or a side-panel resize. const update = () => { const width = mainElement.clientWidth; setContentWidth(previous => - previous !== null && contentBreakpointFor(previous) === contentBreakpointFor(width) ? previous : width, + previous !== null && contentStepFor(previous) === contentStepFor(width) ? previous : width, ); }; update(); diff --git a/openframe-frontend-core/src/components/ui/date-picker.test.tsx b/openframe-frontend-core/src/components/ui/date-picker.test.tsx new file mode 100644 index 0000000000..94c66d1d7e --- /dev/null +++ b/openframe-frontend-core/src/components/ui/date-picker.test.tsx @@ -0,0 +1,38 @@ +import { render, screen } from '@testing-library/react'; +import { describe, expect, it } from 'vitest'; +import { DatePicker, DatePickerInput, DatePickerInputSimple } from './date-picker'; + +/** A picker's label names its trigger, so a click on it opens the calendar and assistive tech reads the field's name. */ +describe('date picker labels', () => { + it('lets a label outside the picker name its trigger', () => { + render( + <> + + + , + ); + expect(screen.getByLabelText('Leaving date').tagName).toBe('BUTTON'); + }); + + it.each([ + ['DatePicker', ], + ['DatePickerInput', ], + ['DatePickerInputSimple', ], + ])('ties its own label to the trigger (%s)', (_, picker) => { + render(picker); + expect(screen.getByLabelText('Start date').tagName).toBe('BUTTON'); + }); + + // The label is now the trigger's whole name, so the date it shows reaches assistive tech as its description. + it.each([ + ['DatePicker', ], + ['DatePickerInput', ], + [ + 'DatePickerInputSimple', + , + ], + ])('describes the trigger by the date it shows (%s)', (_, picker) => { + render(picker); + expect(screen.getByLabelText('Start date')).toHaveAccessibleDescription(/2026/); + }); +}); diff --git a/openframe-frontend-core/src/components/ui/date-picker.tsx b/openframe-frontend-core/src/components/ui/date-picker.tsx index 45d744e9f0..5d7f17ed22 100644 --- a/openframe-frontend-core/src/components/ui/date-picker.tsx +++ b/openframe-frontend-core/src/components/ui/date-picker.tsx @@ -42,6 +42,8 @@ export interface DatePickerBaseProps { error?: string; /** When true, renders red error border */ invalid?: boolean; + /** The trigger button's id: a label drawn outside the picker names it with `htmlFor`. */ + id?: string; } export interface SingleDatePickerProps extends DatePickerBaseProps { @@ -69,6 +71,10 @@ export type DatePickerProps = SingleDatePickerProps | RangeDatePickerProps; const defaultFormatDate = (date: Date): string => formatDateWithTimezone(date, VIEWER_TIMEZONE, 'numeric', { viewerLocale: true }); +// A label tied to the trigger (`id`) becomes the button's whole accessible name, so the date it shows would go unread: +// the trigger is described by its value instead. +const triggerValueId = (id: string | undefined) => (id ? `${id}-value` : undefined); + const formatDateRange = (range: DateRange | undefined, formatFn: (date: Date) => string): string => { if (!range?.from) return ''; if (!range.to) return formatFn(range.from); @@ -667,6 +673,7 @@ export function DatePicker(props: DatePickerProps) { label, error, invalid = false, + id, } = props; const [open, setOpen] = useState(false); @@ -701,6 +708,8 @@ export function DatePicker(props: DatePickerProps) {