Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: Validate acl access depending on program param [DHIS2-17070][2.39] #17338

Merged
merged 3 commits into from
May 6, 2024
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
Expand Up @@ -308,6 +308,25 @@ public TrackedEntityInstance getTrackedEntityInstance(
return getTei(daoTrackedEntityInstance, readableAttributes, params, user);
}

@Override
@Transactional(readOnly = true)
public TrackedEntityInstance getTrackedEntityInstanceExcludingACL(
String uid, TrackedEntityInstanceParams params) {

org.hisp.dhis.trackedentity.TrackedEntityInstance daoTrackedEntityInstance =
teiService.getTrackedEntityInstance(uid);
if (daoTrackedEntityInstance == null) {
return null;
}

User user = currentUserService.getCurrentUser();

Set<TrackedEntityAttribute> readableAttributes =
trackedEntityAttributeService.getAllUserReadableTrackedEntityAttributes(user);

return getTei(daoTrackedEntityInstance, readableAttributes, params, user);
}

private org.hisp.dhis.trackedentity.TrackedEntityInstance createDAOTrackedEntityInstance(
TrackedEntityInstance dtoEntityInstance,
ImportOptions importOptions,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,9 @@ TrackedEntityInstance getTrackedEntityInstance(
TrackedEntityInstanceParams params,
User user);

TrackedEntityInstance getTrackedEntityInstanceExcludingACL(
String uid, TrackedEntityInstanceParams params);

// -------------------------------------------------------------------------
// CREATE, UPDATE or DELETE
// -------------------------------------------------------------------------
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -154,7 +154,9 @@ class TrackedEntityInstanceServiceTest extends TransactionalIntegrationTest {

private FileResource fileResource;

private User user;
private User adminUser;

private User regularUser;

@Override
protected void setUpTest() throws Exception {
Expand All @@ -163,7 +165,8 @@ protected void setUpTest() throws Exception {
fileResourceService.saveFileResource(fileResource, "fileResource".getBytes());

userService = _userService;
user = createAndAddAdminUser(AUTHORITY_ALL);
adminUser = createAndAddAdminUser(AUTHORITY_ALL);
regularUser = createUserWithAuth("regular-user");

organisationUnitA = createOrganisationUnit('A');
organisationUnitB = createOrganisationUnit('B');
Expand Down Expand Up @@ -721,19 +724,19 @@ void shouldSetCreatedAndUpdatedByUserInfoWhenCreateTei() {

ImportSummaries importSummaries =
trackedEntityInstanceService.addTrackedEntityInstances(
List.of(tei), new ImportOptions().setUser(user));
List.of(tei), new ImportOptions().setUser(adminUser));

assertAll(
() -> assertEquals(ImportStatus.SUCCESS, importSummaries.getStatus()),
() ->
assertEquals(
UserInfoSnapshot.from(user),
UserInfoSnapshot.from(adminUser),
trackedEntityInstanceService
.getTrackedEntityInstance(tei.getTrackedEntityInstance())
.getCreatedByUserInfo()),
() ->
assertEquals(
UserInfoSnapshot.from(user),
UserInfoSnapshot.from(adminUser),
trackedEntityInstanceService
.getTrackedEntityInstance(tei.getTrackedEntityInstance())
.getLastUpdatedByUserInfo()));
Expand All @@ -746,13 +749,13 @@ void shouldSetUpdatedByUserInfoWhenUpdateTei() {

ImportSummary importSummaries =
trackedEntityInstanceService.updateTrackedEntityInstance(
tei, null, new ImportOptions().setUser(user), true);
tei, null, new ImportOptions().setUser(adminUser), true);

assertAll(
() -> assertEquals(ImportStatus.SUCCESS, importSummaries.getStatus()),
() ->
assertEquals(
UserInfoSnapshot.from(user),
UserInfoSnapshot.from(adminUser),
trackedEntityInstanceService
.getTrackedEntityInstance(tei.getTrackedEntityInstance())
.getLastUpdatedByUserInfo()));
Expand All @@ -766,7 +769,7 @@ void shouldSetLastUpdatedInfoWhenDeleteTe() {

dbmsManager.clearSession();

injectSecurityContext(user);
injectSecurityContext(adminUser);

ImportSummary importSummaries =
trackedEntityInstanceService.deleteTrackedEntityInstance(maleA.getUid());
Expand All @@ -780,13 +783,24 @@ void shouldSetLastUpdatedInfoWhenDeleteTe() {
() -> assertEquals(ImportStatus.SUCCESS, importSummaries.getStatus()),
() ->
assertEquals(
UserInfoSnapshot.from(user).getUid(),
UserInfoSnapshot.from(adminUser).getUid(),
getTrackedEntity(maleA.getUid()).getLastUpdatedByUserInfo().getUid()),
() ->
assertTrue(
entityAfter.getLastUpdated().getTime() > entityBefore.getLastUpdated().getTime()));
}

@Test
void shouldReturnTEIEvenIfTrackedEntityTypeNotAccessible() {
injectSecurityContext(regularUser);

TrackedEntityInstance trackedEntityInstance =
trackedEntityInstanceService.getTrackedEntityInstanceExcludingACL(
maleA.getUid(), TrackedEntityInstanceParams.TRUE);

assertEquals(maleA.getUid(), trackedEntityInstance.getTrackedEntityInstance());
}

/** Get with the current session because some Store exclude deleted */
public org.hisp.dhis.trackedentity.TrackedEntityInstance getTrackedEntity(String uid) {

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -421,6 +421,60 @@ void shouldFailToGetTrackedEntitiesWhenOrderingByIllegalField() {
assertContains("Cannot order by 'invalid'", response.getString("message").string());
}

@Test
void shouldFailWhenRequestingTEIAndTrackedEntityTypeNotAccessible() {
User unauthorizedUser = createUserWithId("unauthorized", CodeGenerator.generateUid());
this.userService.updateUser(unauthorizedUser);
this.switchContextToUser(unauthorizedUser);
TrackedEntityInstance trackedEntityInstance = trackedEntityInstance();

assertContains(
"User has no data read access to tracked entity type",
GET("/tracker/trackedEntities/{trackedEntityInstance}", trackedEntityInstance.getUid())
.error(HttpStatus.CONFLICT)
.getMessage());
}

@Test
void shouldFailWhenRequestingTEIAndNoProgramAccessible() {
User unauthorizedUser = createUserWithId("unauthorized", CodeGenerator.generateUid());
this.userService.updateUser(unauthorizedUser);
TrackedEntityType trackedEntityType = trackedEntityType('T', unauthorizedUser);
TrackedEntityInstance trackedEntityInstance = trackedEntityInstance(trackedEntityType);

this.switchContextToUser(unauthorizedUser);

assertContains(
"User has no access to any program",
GET("/tracker/trackedEntities/{trackedEntityInstance}", trackedEntityInstance.getUid())
.error(HttpStatus.CONFLICT)
.getMessage());
}

@Test
void shouldReturnTrackedEntityInstanceWhenAtLeastOneProgramAccessible() {
User authorizedUser = createUserWithId("authorized", CodeGenerator.generateUid());
authorizedUser.addOrganisationUnit(orgUnit);
authorizedUser.setTeiSearchOrganisationUnits(Set.of(orgUnit));
this.userService.updateUser(authorizedUser);
TrackedEntityType trackedEntityType = trackedEntityType('T', authorizedUser);
TrackedEntityInstance trackedEntityInstance = trackedEntityInstance(trackedEntityType);
Program program = createProgram('P');
program.addOrganisationUnit(orgUnit);
program.getSharing().setOwner(authorizedUser);
program.getSharing().addUserAccess(userAccess(authorizedUser));
program.setTrackedEntityType(trackedEntityType);
manager.save(program, false);

this.switchContextToUser(authorizedUser);

JsonObject json =
GET("/tracker/trackedEntities/{id}", trackedEntityInstance.getUid()).content(HttpStatus.OK);

assertFalse(json.isEmpty());
assertEquals(trackedEntityInstance.getUid(), json.getString("trackedEntity").string());
}

private ProgramStageInstance programStageInstanceWithDataValue(ProgramInstance programInstance) {
ProgramStageInstance programStageInstance =
new ProgramStageInstance(
Expand Down Expand Up @@ -533,6 +587,15 @@ private TrackedEntityType trackedEntityType(char uniqueChar) {
return type;
}

private TrackedEntityType trackedEntityType(char uniqueChar, User user) {
TrackedEntityType type = createTrackedEntityType(uniqueChar);
type.getSharing().setOwner(user);
type.getSharing().setPublicAccess(AccessStringHelper.DEFAULT);
type.getSharing().addUserAccess(userAccess(user));
manager.save(type, false);
return type;
}

private TrackedEntityInstance trackedEntityInstance() {
TrackedEntityInstance tei = trackedEntityInstance(orgUnit);
manager.save(tei, false);
Expand Down Expand Up @@ -571,6 +634,13 @@ private UserAccess userAccess() {
return a;
}

private UserAccess userAccess(User user) {
UserAccess a = new UserAccess();
a.setUser(user);
a.setAccess(AccessStringHelper.FULL);
return a;
}

private RelationshipType relationshipTypeAccessible(
RelationshipEntity from, RelationshipEntity to) {
RelationshipType type = relationshipType(from, to);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,9 +42,6 @@
import org.hisp.dhis.dxf2.webmessage.WebMessageException;
import org.hisp.dhis.program.Program;
import org.hisp.dhis.program.ProgramService;
import org.hisp.dhis.trackedentity.TrackedEntityAttribute;
import org.hisp.dhis.trackedentity.TrackedEntityType;
import org.hisp.dhis.trackedentity.TrackedEntityTypeService;
import org.hisp.dhis.trackedentity.TrackerAccessManager;
import org.hisp.dhis.trackedentity.TrackerOwnershipManager;
import org.hisp.dhis.user.CurrentUserService;
Expand All @@ -65,21 +62,18 @@ class TrackedEntitiesSupportService {

@NonNull private final org.hisp.dhis.trackedentity.TrackedEntityInstanceService instanceService;

@NonNull private final TrackedEntityTypeService trackedEntityTypeService;

@SneakyThrows
public TrackedEntityInstance getTrackedEntityInstance(
String id, String pr, TrackedEntityInstanceParams trackedEntityInstanceParams) {
User user = currentUserService.getCurrentUser();

TrackedEntityInstance trackedEntityInstance =
trackedEntityInstanceService.getTrackedEntityInstance(id, trackedEntityInstanceParams);

if (trackedEntityInstance == null) {
throw new NotFoundException("TrackedEntityInstance", id);
}
TrackedEntityInstance trackedEntityInstance = null;

if (pr != null) {
trackedEntityInstance =
trackedEntityInstanceService.getTrackedEntityInstanceExcludingACL(
id, trackedEntityInstanceParams);

Program program = programService.getProgram(pr);

if (program == null) {
Expand Down Expand Up @@ -112,21 +106,11 @@ public TrackedEntityInstance getTrackedEntityInstance(
}
} else {
// return only tracked entity type attributes
trackedEntityInstance =
trackedEntityInstanceService.getTrackedEntityInstance(id, trackedEntityInstanceParams);

TrackedEntityType trackedEntityType =
trackedEntityTypeService.getTrackedEntityType(
trackedEntityInstance.getTrackedEntityType());

if (trackedEntityType != null) {
List<String> tetAttributes =
trackedEntityType.getTrackedEntityAttributes().stream()
.map(TrackedEntityAttribute::getUid)
.collect(Collectors.toList());

trackedEntityInstance.setAttributes(
trackedEntityInstance.getAttributes().stream()
.filter(att -> tetAttributes.contains(att.getAttribute()))
.collect(Collectors.toList()));
if (trackedEntityInstance == null) {
throw new NotFoundException(TrackedEntityInstance.class.getSimpleName(), id);
}
}

Expand Down
Loading