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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.openframe.api.dto.rmm.software;

import com.openframe.data.document.device.Machine;
import com.openframe.data.document.rmm.software.SoftwareAutoUpdateStatus;
import lombok.Builder;
import lombok.Data;

Expand All @@ -11,4 +12,5 @@ public class SoftwareOnDeviceResponse {
private Machine device;
private String softwareVersion;
private SoftwareOnDeviceStatus status;
private SoftwareAutoUpdateStatus autoUpdate;
}
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ public class SoftwarePackageInput {

private BrewPackageType brewPackageType;
private String version;
private String softwareId;
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.openframe.api.dto.rmm.software;

import com.openframe.data.document.rmm.software.SoftwareAutoUpdateStatus;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
Expand All @@ -21,4 +22,5 @@ public class SoftwareResponse {
private Integer devicesCount;
private SoftwareVulnerabilitySummaryResponse vulnerabilitySummary;
private Boolean cpeMatched;
private SoftwareAutoUpdateStatus autoUpdate;
}
Original file line number Diff line number Diff line change
Expand Up @@ -16,4 +16,5 @@ public class SoftwareSchedulePackageInput {
private String packageName;

private BrewPackageType brewPackageType;
private String softwareId;
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
package com.openframe.api.service.rmm.software;

import com.openframe.api.dto.rmm.software.SoftwareOnDeviceResponse;
import com.openframe.api.dto.rmm.software.SoftwareResponse;
import com.openframe.data.document.rmm.software.PackageAutoUpdatePolicy;
import com.openframe.data.document.rmm.software.SoftwareAutoUpdateStatus;
import com.openframe.data.repository.rmm.PackageAutoUpdatePolicyRepository;
import com.openframe.data.service.TenantIdProvider;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;

import static java.util.stream.Collectors.collectingAndThen;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.toList;

// AUTO-UPDATE of a Software, from the policies linked to it: ON while any of them keeps the package updated,
// OFF once all are turned off, null when it has none.
@Slf4j
@Service
@ConditionalOnProperty(name = "openframe.rmm.software.enabled", havingValue = "true")
@RequiredArgsConstructor
public class SoftwareAutoUpdateService {

private final PackageAutoUpdatePolicyRepository policyRepository;
private final TenantIdProvider tenantIdProvider;

public void turnOff(String softwareId, String actor) {
long turnedOff = policyRepository.disableBySoftwareId(tenantIdProvider.getTenantId(), softwareId, actor);
log.info("Auto-update turned off softwareId={} policies={} actor={}", softwareId, turnedOff, actor);
}

public void applyToSoftware(List<SoftwareResponse> rows) {
List<String> softwareIds = ids(rows, SoftwareResponse::getId);
if (softwareIds.isEmpty()) {
return;
}
Map<String, SoftwareAutoUpdateStatus> statuses = statusBy(
policyRepository.findByTenantIdAndSoftwareIdIn(tenantIdProvider.getTenantId(), softwareIds),
PackageAutoUpdatePolicy::getSoftwareId);
rows.forEach(row -> row.setAutoUpdate(statuses.get(row.getId())));
}

public void applyToSoftwareOnDevice(String machineId, List<SoftwareResponse> rows) {
List<String> softwareIds = ids(rows, SoftwareResponse::getId);
if (softwareIds.isEmpty()) {
return;
}
Map<String, SoftwareAutoUpdateStatus> statuses = statusBy(
policyRepository.findByTenantIdAndMachineIdAndSoftwareIdIn(tenantIdProvider.getTenantId(), machineId,
softwareIds),
PackageAutoUpdatePolicy::getSoftwareId);
rows.forEach(row -> row.setAutoUpdate(statuses.get(row.getId())));
}

public void applyToDevices(String softwareId, List<SoftwareOnDeviceResponse> rows) {
List<String> machineIds = ids(rows, SoftwareAutoUpdateService::machineId);
if (machineIds.isEmpty()) {
return;
}
Map<String, SoftwareAutoUpdateStatus> statuses = statusBy(
policyRepository.findByTenantIdAndSoftwareIdAndMachineIdIn(tenantIdProvider.getTenantId(), softwareId,
machineIds),
PackageAutoUpdatePolicy::getMachineId);
rows.forEach(row -> row.setAutoUpdate(statuses.get(machineId(row))));
}

private static String machineId(SoftwareOnDeviceResponse row) {
return row.getDevice() == null ? null : row.getDevice().getMachineId();
}

private static <T> List<String> ids(List<T> rows, Function<T, String> id) {
return rows.stream().map(id).filter(Objects::nonNull).distinct().toList();
}

private static Map<String, SoftwareAutoUpdateStatus> statusBy(List<PackageAutoUpdatePolicy> policies,
Function<PackageAutoUpdatePolicy, String> key) {
return policies.stream().collect(groupingBy(key, collectingAndThen(toList(), SoftwareAutoUpdateService::statusOf)));
}

private static SoftwareAutoUpdateStatus statusOf(List<PackageAutoUpdatePolicy> policies) {
return policies.stream().anyMatch(PackageAutoUpdatePolicy::isEnabled)
? SoftwareAutoUpdateStatus.ON
: SoftwareAutoUpdateStatus.OFF;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -308,6 +308,7 @@ private static List<SoftwareSchedulePackageInput> toSchedulePackages(List<Softwa
i.setPackageManager(p.getPackageManager());
i.setPackageName(p.getPackageName());
i.setBrewPackageType(p.getBrewPackageType());
i.setSoftwareId(p.getSoftwareId());
return i;
})
.toList();
Expand Down Expand Up @@ -359,6 +360,7 @@ private static List<SoftwareBundlePackage> toDomainPackages(List<SoftwarePackage
.packageName(p.getPackageName())
.brewPackageType(p.getBrewPackageType())
.version(p.getVersion())
.softwareId(p.getSoftwareId())
.build())
.toList();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
import com.openframe.api.dto.shared.SortDirection;
import com.openframe.api.dto.shared.SortInput;
import com.openframe.core.exception.BadRequestException;
import com.openframe.core.exception.NotFoundException;
import com.openframe.api.service.rmm.fleet.DeviceHostInventoryLoader;
import com.openframe.api.service.rmm.fleet.FleetCalls;
import com.openframe.api.service.rmm.fleet.FleetDeviceCountEnricher;
Expand Down Expand Up @@ -90,6 +91,7 @@ public class SoftwareInventoryService {
private final com.openframe.api.service.rmm.fleet.FleetHostMachineResolver hostMachineResolver;
private final TenantIdProvider tenantIdProvider;
private final DeviceHostInventoryLoader deviceHostInventoryLoader;
private final SoftwareAutoUpdateService autoUpdateService;

@Value("${TENANT_ID:}")
private String tenantIdEnv;
Expand Down Expand Up @@ -123,10 +125,16 @@ public Optional<SoftwareResponse> findById(String softwareId) {
if (!fleetPaging) {
enrichRealDevicesCount(List.of(row));
}
autoUpdateService.applyToSoftware(List.of(row));
return row;
});
}

public SoftwareResponse turnOffAutoUpdate(String softwareId, String actor) {
autoUpdateService.turnOff(softwareId, actor);
return findById(softwareId).orElseThrow(() -> new NotFoundException("Software not found: " + softwareId));
}

public PageResult<SoftwareResponse> listSoftware(String search, int page, Integer perPage,
SortInput sort, Boolean vulnerable) {
String field = sort == null ? null : sort.getField();
Expand All @@ -135,7 +143,7 @@ public PageResult<SoftwareResponse> listSoftware(String search, int page, Intege
throw new BadRequestException("Unknown sort field '" + field + "'. Sortable fields: " + SORTABLE_FIELDS);
}
if (fleetPaging) {
return softwarePageFromFleet(search, page, perPage, sort, vulnerable);
return withAutoUpdate(softwarePageFromFleet(search, page, perPage, sort, vulnerable));
}

List<SoftwareTitle> titles = fetchAllTitles(search, vulnerable);
Expand All @@ -148,7 +156,12 @@ public PageResult<SoftwareResponse> listSoftware(String search, int page, Intege
List<SoftwareResponse> ordered = field == null
? withDevices
: withDevices.stream().sorted(comparatorFor(field, desc)).toList();
return paginateList(ordered, page, perPage);
return withAutoUpdate(paginateList(ordered, page, perPage));
}

private PageResult<SoftwareResponse> withAutoUpdate(PageResult<SoftwareResponse> page) {
autoUpdateService.applyToSoftware(page.items());
return page;
}

private PageResult<SoftwareResponse> softwarePageFromFleet(String search, int page, Integer perPage,
Expand Down Expand Up @@ -336,7 +349,9 @@ public PageResult<SoftwareOnDeviceResponse> listDevicesForSoftware(String softwa
List<SoftwareOnDeviceResponse> all = allDevicesForSoftware(softwareId, search).stream()
.filter(row -> matchesStatusFilter(row, filter))
.toList();
return paginateList(all, page, perPage);
PageResult<SoftwareOnDeviceResponse> result = paginateList(all, page, perPage);
autoUpdateService.applyToDevices(softwareId, result.items());
return result;
}

private static boolean matchesStatusFilter(SoftwareOnDeviceResponse row, SoftwareOnDeviceFilterInput filter) {
Expand All @@ -356,7 +371,9 @@ public PageResult<SoftwareResponse> listSoftwareForDevice(String machineId, Soft
enrichDevicesCountFromHosts(rows);
}
List<SoftwareResponse> ordered = rows.stream().sorted(order).toList();
return paginateList(ordered, page, perPage);
PageResult<SoftwareResponse> result = paginateList(ordered, page, perPage);
autoUpdateService.applyToSoftwareOnDevice(machineId, result.items());
return result;
}

public SoftwareFilters getDeviceSoftwareFilters(String machineId, String search) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -282,6 +282,7 @@ private static List<SoftwareSchedulePackage> toPackages(List<SoftwareSchedulePac
.packageManager(p.getPackageManager())
.packageName(p.getPackageName())
.brewPackageType(p.getBrewPackageType())
.softwareId(p.getSoftwareId())
.build())
.toList();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
package com.openframe.api.service.rmm.software;

import com.openframe.api.dto.rmm.software.SoftwareOnDeviceResponse;
import com.openframe.api.dto.rmm.software.SoftwareResponse;
import com.openframe.data.document.device.Machine;
import com.openframe.data.document.rmm.software.PackageAutoUpdatePolicy;
import com.openframe.data.document.rmm.software.SoftwareAutoUpdateStatus;
import com.openframe.data.repository.rmm.PackageAutoUpdatePolicyRepository;
import com.openframe.data.service.TenantIdProvider;
import org.junit.jupiter.api.BeforeEach;
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.tuple;
import static org.mockito.ArgumentMatchers.anyCollection;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.lenient;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;

@ExtendWith(MockitoExtension.class)
class SoftwareAutoUpdateServiceTest {

private static final String TENANT = "t1";

@Mock private PackageAutoUpdatePolicyRepository policyRepository;
@Mock private TenantIdProvider tenantIdProvider;

@InjectMocks private SoftwareAutoUpdateService service;

@BeforeEach
void setUp() {
lenient().when(tenantIdProvider.getTenantId()).thenReturn(TENANT);
}

@Test
void software_onWhileAnyDeviceKeepsIt_offOnceAllAreOff_nullWithoutPolicies() {
when(policyRepository.findByTenantIdAndSoftwareIdIn(eq(TENANT), anyCollection())).thenReturn(List.of(
policy("m1", "chrome", true), policy("m2", "chrome", false),
policy("m1", "slack", false), policy("m2", "slack", false)));
List<SoftwareResponse> rows = List.of(software("chrome"), software("slack"), software("zoom"));

service.applyToSoftware(rows);

assertThat(rows).extracting(SoftwareResponse::getId, SoftwareResponse::getAutoUpdate).containsExactly(
tuple("chrome", SoftwareAutoUpdateStatus.ON),
tuple("slack", SoftwareAutoUpdateStatus.OFF),
tuple("zoom", null));
}

@Test
void softwareOnDevice_readsOnlyThatDevicesPolicies() {
when(policyRepository.findByTenantIdAndMachineIdAndSoftwareIdIn(eq(TENANT), eq("m2"), anyCollection()))
.thenReturn(List.of(policy("m2", "chrome", false)));
List<SoftwareResponse> rows = List.of(software("chrome"), software("slack"));

service.applyToSoftwareOnDevice("m2", rows);

assertThat(rows).extracting(SoftwareResponse::getAutoUpdate)
.containsExactly(SoftwareAutoUpdateStatus.OFF, null);
}

@Test
void devices_eachDeviceItsOwnState() {
when(policyRepository.findByTenantIdAndSoftwareIdAndMachineIdIn(eq(TENANT), eq("chrome"), anyCollection()))
.thenReturn(List.of(policy("m1", "chrome", true), policy("m2", "chrome", false)));
List<SoftwareOnDeviceResponse> rows = List.of(onDevice("m1"), onDevice("m2"), onDevice("m3"));

service.applyToDevices("chrome", rows);

assertThat(rows).extracting(SoftwareOnDeviceResponse::getAutoUpdate)
.containsExactly(SoftwareAutoUpdateStatus.ON, SoftwareAutoUpdateStatus.OFF, null);
}

@Test
void emptyPage_noLookup() {
service.applyToSoftware(List.of());
service.applyToDevices("chrome", List.of());

verifyNoInteractions(policyRepository);
}

@Test
void turnOff_disablesTheSoftwaresPolicies() {
service.turnOff("chrome", "admin@x");

verify(policyRepository).disableBySoftwareId(TENANT, "chrome", "admin@x");
}

private static PackageAutoUpdatePolicy policy(String machineId, String softwareId, boolean enabled) {
return PackageAutoUpdatePolicy.builder()
.tenantId(TENANT).machineId(machineId).softwareId(softwareId).enabled(enabled).build();
}

private static SoftwareResponse software(String id) {
return SoftwareResponse.builder().id(id).build();
}

private static SoftwareOnDeviceResponse onDevice(String machineId) {
Machine machine = new Machine();
machine.setMachineId(machineId);
return SoftwareOnDeviceResponse.builder().device(machine).build();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -251,13 +251,15 @@ void submit_installWithUpdateSettings_rejectedNothingSaved() {
}

@Test
@DisplayName("submit SCHEDULED UPDATE: the settings travel to the schedule it creates")
@DisplayName("submit SCHEDULED UPDATE: the settings and each package's Software travel to the schedule it creates")
void submit_scheduledUpdate_settingsForwardedToTheSchedule() {
SoftwareBundle draft = pending(SoftwareBundleMode.NOW, null, List.of("m1"));
when(bundleRepository.findByTenantIdAndId(TENANT, BUNDLE_ID)).thenReturn(Optional.of(draft));
when(machinePlatformResolver.osTypesByMachineId(any())).thenReturn(java.util.Map.of("m1", OsType.MAC_OS));
when(softwareScheduleService.create(any(), eq(USER))).thenReturn(SoftwareScheduleResponse.builder().id("s1").build());
SubmitSoftwareBundleInput input = submitInput(brewPkg("slack"));
SoftwarePackageInput slack = brewPkg("slack");
slack.setSoftwareId("title-7");
SubmitSoftwareBundleInput input = submitInput(slack);
input.setAction(SoftwareAction.UPDATE);
SoftwareBundleScheduleInput schedule = new SoftwareBundleScheduleInput();
schedule.setStartAt(Instant.parse("2026-09-15T02:00:00Z"));
Expand All @@ -274,6 +276,8 @@ void submit_scheduledUpdate_settingsForwardedToTheSchedule() {
verify(softwareScheduleService).create(created.capture(), eq(USER));
assertThat(created.getValue().getUpdateSettings()).isSameAs(settings);
assertThat(created.getValue().getAutoUpdate()).isSameAs(autoUpdate);
assertThat(created.getValue().getPackages()).singleElement()
.satisfies(p -> assertThat(p.getSoftwareId()).isEqualTo("title-7"));
}

private static PackageUpdateSettingsInput settingsInput(PackageUpdateMode mode, Long deadlineSeconds, int countdownSeconds) {
Expand Down
Loading
Loading