Skip to content

Commit

Permalink
Merge pull request #1158 from ds-lcapellino/bug/639-update-accepted-p…
Browse files Browse the repository at this point in the history
…olicies-after-crud

bug: #639 update policies provider after crud operations on policies
  • Loading branch information
ds-mwesener authored Jul 4, 2024
2 parents ca8c1e7 + c520d03 commit 8fa48d9
Show file tree
Hide file tree
Showing 10 changed files with 318 additions and 53 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,11 +18,15 @@
********************************************************************************/
package org.eclipse.tractusx.traceability.policies.infrastructure;

import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.irs.edc.client.policy.AcceptedPoliciesProvider;
import org.eclipse.tractusx.irs.edc.client.policy.AcceptedPolicy;
import org.eclipse.tractusx.irs.edc.client.policy.Constraint;
import org.eclipse.tractusx.irs.edc.client.policy.Constraints;
import org.eclipse.tractusx.irs.edc.client.policy.Permission;
import org.eclipse.tractusx.irs.edc.client.policy.Policy;
import org.eclipse.tractusx.traceability.policies.domain.PolicyRepository;
import policies.response.CreatePolicyResponse;
import policies.response.IrsPolicyResponse;
Expand All @@ -41,11 +45,12 @@

@Slf4j
@Service
@RequiredArgsConstructor
@AllArgsConstructor
public class PolicyRepositoryImpl implements PolicyRepository {

private final PolicyClient policyClient;
private final TraceabilityProperties traceabilityProperties;
private AcceptedPoliciesProvider.DefaultAcceptedPoliciesProvider defaultAcceptedPoliciesProvider;

@Override
public Map<String, List<IrsPolicyResponse>> getPolicies() {
Expand All @@ -69,15 +74,15 @@ public Map<String, Optional<IrsPolicyResponse>> getPolicy(String policyId) {
}



@Override
public void createPolicyBasedOnAppConfig() {
log.info("Check if irs policy exists");
final Map<String, List<IrsPolicyResponse>> irsPolicies = this.policyClient.getPolicies();
final List<String> irsPoliciesIds = irsPolicies.values().stream()
.flatMap(List::stream)
.map(irsPolicyResponse -> irsPolicyResponse.payload().policyId())
.toList(); log.info("Irs has following policies: {}", irsPoliciesIds);
.toList();
log.info("Irs has following policies: {}", irsPoliciesIds);

log.info("Required constraints - 2 -");
log.info("First constraint requirements: leftOperand {} operator {} and rightOperand {}", traceabilityProperties.getLeftOperand(), traceabilityProperties.getOperatorType(), traceabilityProperties.getRightOperand());
Expand All @@ -90,25 +95,29 @@ public void createPolicyBasedOnAppConfig() {
} else {
checkAndUpdatePolicy(matchingPolicy);
}
updateAcceptedPoliciesProvider();
}

@Override
public void deletePolicy(String policyId) {
this.policyClient.deletePolicy(policyId);
updateAcceptedPoliciesProvider();
}

@Override
public void updatePolicy(UpdatePolicyRequest updatePolicyRequest) {
this.policyClient.updatePolicy(updatePolicyRequest);
updateAcceptedPoliciesProvider();
}

@Override
public CreatePolicyResponse createPolicy(RegisterPolicyRequest registerPolicyRequest) {
return this.policyClient.createPolicy(registerPolicyRequest);
CreatePolicyResponse policy = this.policyClient.createPolicy(registerPolicyRequest);
updateAcceptedPoliciesProvider();
return policy;
}



private IrsPolicyResponse findMatchingPolicy(Map<String, List<IrsPolicyResponse>> irsPolicies) {
return irsPolicies.values().stream()
.flatMap(List::stream)
Expand Down Expand Up @@ -141,8 +150,6 @@ private Stream<Constraint> getConstraintsStream(Permission permission) {
}




private void createMissingPolicies() {
log.info("Irs policy does not exist creating {}", traceabilityProperties.getRightOperand());
this.policyClient.createPolicyFromAppConfig();
Expand All @@ -160,4 +167,19 @@ private boolean isPolicyExpired(IrsPolicyResponse requiredPolicy) {
return traceabilityProperties.getValidUntil().isAfter(requiredPolicy.validUntil());
}

private void updateAcceptedPoliciesProvider() {
defaultAcceptedPoliciesProvider.removeAcceptedPolicies(defaultAcceptedPoliciesProvider.getAcceptedPolicies(null));
// Flatten the map into a list of IrsPolicyResponse objects
List<IrsPolicyResponse> irsPolicyResponses = getPolicies().values().stream()
.flatMap(List::stream)
.toList();

// Map the IrsPolicyResponse objects to AcceptedPolicy objects
List<AcceptedPolicy> irsPolicies = irsPolicyResponses.stream().map(response -> {
Policy policy = new Policy(response.payload().policyId(), response.payload().policy().getCreatedOn(), response.validUntil(), response.payload().policy().getPermissions());
return new AcceptedPolicy(policy, response.validUntil());
}).toList();
defaultAcceptedPoliciesProvider.addAcceptedPolicies(irsPolicies);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@

package org.eclipse.tractusx.traceability.assets.infrastructure.base.irs;

import org.eclipse.tractusx.irs.edc.client.policy.AcceptedPoliciesProvider;
import org.eclipse.tractusx.irs.edc.client.policy.Constraint;
import org.eclipse.tractusx.irs.edc.client.policy.Constraints;
import org.eclipse.tractusx.irs.edc.client.policy.Operator;
Expand All @@ -43,6 +44,7 @@
import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
Expand All @@ -56,6 +58,10 @@ class PolicyRepositoryImplTest {
@Mock
TraceabilityProperties traceabilityProperties;

@Mock
AcceptedPoliciesProvider.DefaultAcceptedPoliciesProvider defaultAcceptedPoliciesProvider;


@Mock
private PolicyClient policyClient;

Expand All @@ -71,6 +77,8 @@ void givenNoPolicyExist_whenCreateIrsPolicyIfMissing_thenCreateApplicationConfig
// then
verify(policyClient, times(1))
.createPolicyFromAppConfig();
verify(defaultAcceptedPoliciesProvider, times(1))
.addAcceptedPolicies(any());
}

@Test
Expand All @@ -94,6 +102,8 @@ void givenPolicyExist_whenCreateIrsPolicyIfMissing_thenDoNotCreateApplicationCon

// then
verifyNoMoreInteractions(policyClient);
verify(defaultAcceptedPoliciesProvider, times(1))
.addAcceptedPolicies(any());
}

@Test
Expand All @@ -119,6 +129,8 @@ void givenOutdatedPolicyExist_whenCreatePolicyBasedOnAppConfig_thenUpdateIt() {
// then
verify(policyClient, times(1)).deletePolicy(traceabilityProperties.getRightOperand());
verify(policyClient, times(1)).createPolicyFromAppConfig();
verify(defaultAcceptedPoliciesProvider, times(1))
.addAcceptedPolicies(any());
}

@Test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,6 +172,26 @@ public void irsApiDeletesPolicy(String policyId) {
);
}

public void irsApiReturnsExpiredPolicy() {
whenHttp(restitoProvider.stubServer()).match(
Condition.get("/irs/policies")
).then(
Action.status(HttpStatus.OK_200),
Action.header("Content-Type", "application/json"),
restitoProvider.jsonResponseFromFile("./stubs/irs/policies/response_200_get_policies_EXPIRED.json")
);
}

public void irsApiReturnsMismatchingPolicy() {
whenHttp(restitoProvider.stubServer()).match(
Condition.get("/irs/policies")
).then(
Action.status(HttpStatus.OK_200),
Action.header("Content-Type", "application/json"),
restitoProvider.jsonResponseFromFile("./stubs/irs/policies/response_200_get_policies_CONSTRAINTS_MISMATCHING.json")
);
}

private String readFile(String filePath) throws IOException {
// Implement reading file content from the specified filePath
// This is a utility method to read the JSON response from a file
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,9 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.List;

Expand Down Expand Up @@ -79,23 +81,16 @@ public class InvestigationPolicyExpirationIT extends IntegrationTestSpecificatio

ObjectMapper objectMapper;


@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("traceability.validUntil", () -> "2020-07-04T16:01:05.309Z");
registry.add("server.port", () -> "9997");
registry.add("management.server.port", () -> "8083");
}

@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
}

@Test
void shouldNotApproveInvestigationStatus_whenPolicyIsExpired() throws JoseException, com.fasterxml.jackson.core.JsonProcessingException {
void shouldNotApproveInvestigationStatus_whenPolicyIsExpired() throws JoseException, com.fasterxml.jackson.core.JsonProcessingException, FileNotFoundException {
// given
irsApiSupport.irsApiReturnsPolicies();
irsApiSupport.irsApiReturnsExpiredPolicy();
irsApiSupport.irsApiCreatesPolicy();
discoveryFinderSupport.discoveryFinderWillReturnEndpointAddress();
discoveryFinderSupport.discoveryFinderWillReturnConnectorEndpoints();
oauth2ApiSupport.oauth2ApiReturnsDtrToken();
Expand All @@ -115,6 +110,18 @@ void shouldNotApproveInvestigationStatus_whenPolicyIsExpired() throws JoseExcept
.receiverBpn("BPNL00000003CNKC")
.build();

// this create will be not used, since irsApiSupport.irsApiReturnsExpiredPolicy(); returns the used policy
// for this test
given()
.contentType(ContentType.JSON)
.header(oAuth2Support.jwtAuthorization(SUPERVISOR))
.when()
.body(ResourceUtils.getFile("classpath:stubs/irs/policies/request_create_policy.json"))
.post("/api/policies")
.then()
.log().all()
.statusCode(200);

// when
val investigationId = notificationApiSupport.createNotificationRequest_withDefaultAssetsStored(oAuth2Support.jwtAuthorization(SUPERVISOR), startInvestigationRequest, 201);

Expand Down Expand Up @@ -148,5 +155,17 @@ void shouldNotApproveInvestigationStatus_whenPolicyIsExpired() throws JoseExcept
.body("content[0].messages[1].errorMessage", Matchers.is("Failed to negotiate contract agreement: Policy from BPNL00000003CNKC has expired."));

notificationMessageSupport.assertMessageSize(2);

//finally
irsApiSupport.irsApiReturnsPolicies();
given()
.contentType(ContentType.JSON)
.header(oAuth2Support.jwtAuthorization(SUPERVISOR))
.when()
.body(ResourceUtils.getFile("classpath:stubs/irs/policies/request_create_policy.json"))
.post("/api/policies")
.then()
.log().all()
.statusCode(200);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -46,7 +46,9 @@
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.DynamicPropertyRegistry;
import org.springframework.test.context.DynamicPropertySource;
import org.springframework.util.ResourceUtils;

import java.io.FileNotFoundException;
import java.util.Collections;
import java.util.List;

Expand Down Expand Up @@ -80,24 +82,16 @@ public class InvestigationPolicyNotSupportedIT extends IntegrationTestSpecificat

ObjectMapper objectMapper;


@DynamicPropertySource
static void dynamicProperties(DynamicPropertyRegistry registry) {
registry.add("traceability.leftOperand", () -> "unsopperted operand");
registry.add("server.port", () -> "9996");
registry.add("management.server.port", () -> "8084");
}

@BeforeEach
void setUp() {
objectMapper = new ObjectMapper();
}

@Disabled
@Test
void shouldNotApproveInvestigationStatus_whenPolicyDoesNotComply() throws JoseException, com.fasterxml.jackson.core.JsonProcessingException {
void shouldNotApproveInvestigationStatus_whenPolicyDoesNotComply() throws JoseException, com.fasterxml.jackson.core.JsonProcessingException, FileNotFoundException {
// given
irsApiSupport.irsApiReturnsPolicies();
irsApiSupport.irsApiReturnsMismatchingPolicy();
irsApiSupport.irsApiCreatesPolicy();
discoveryFinderSupport.discoveryFinderWillReturnEndpointAddress();
discoveryFinderSupport.discoveryFinderWillReturnConnectorEndpoints();
oauth2ApiSupport.oauth2ApiReturnsDtrToken();
Expand All @@ -117,6 +111,17 @@ void shouldNotApproveInvestigationStatus_whenPolicyDoesNotComply() throws JoseEx
.receiverBpn("BPNL00000003CNKC")
.build();

// this create will be not used, since irsApiSupport.irsApiReturnsMismatchingPolicy(); returns the used policy
// for this test
given()
.contentType(ContentType.JSON)
.header(oAuth2Support.jwtAuthorization(SUPERVISOR))
.when()
.body(ResourceUtils.getFile("classpath:stubs/irs/policies/request_create_policy.json"))
.post("/api/policies")
.then()
.log().all()
.statusCode(200);
// when
val investigationId = notificationApiSupport.createNotificationRequest_withDefaultAssetsStored(oAuth2Support.jwtAuthorization(SUPERVISOR), startInvestigationRequest, 201);

Expand Down Expand Up @@ -150,5 +155,17 @@ void shouldNotApproveInvestigationStatus_whenPolicyDoesNotComply() throws JoseEx
.body("content[0].messages[1].errorMessage", Matchers.endsWith("did not match with policy from BPNL00000003CNKC."));

notificationMessageSupport.assertMessageSize(2);

//finally
irsApiSupport.irsApiReturnsPolicies();
given()
.contentType(ContentType.JSON)
.header(oAuth2Support.jwtAuthorization(SUPERVISOR))
.when()
.body(ResourceUtils.getFile("classpath:stubs/irs/policies/request_create_policy.json"))
.post("/api/policies")
.then()
.log().all()
.statusCode(200);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@ void shouldReturnNotFoundGetPolicyById() throws JoseException {
void shouldCreatePolicy() throws JoseException {
// GIVEN
irsApiSupport.irsApiCreatesPolicy();
irsApiSupport.irsApiReturnsPolicies();
Payload payload = Payload.builder().build();
RegisterPolicyRequest request = new RegisterPolicyRequest(Instant.MAX, "abc", payload);

Expand Down Expand Up @@ -141,6 +142,7 @@ void shouldThorwBadRequestCreatePolicy() throws JoseException {
void shouldUpdatePolicy() throws JoseException {
// GIVEN
irsApiSupport.irsApiUpdatesPolicy();
irsApiSupport.irsApiReturnsPolicies();

UpdatePolicyRequest request = new UpdatePolicyRequest(List.of("abc"), List.of("abc"), Instant.MAX);

Expand All @@ -161,6 +163,7 @@ void shouldDeletePolicy() throws JoseException {
// GIVEN
String policyId = "policy1";
irsApiSupport.irsApiDeletesPolicy(policyId);
irsApiSupport.irsApiReturnsPolicies();

// when/then
given()
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"validUntil": "2024-07-04T00:00:00.000000000Z",
"businessPartnerNumber": "BPNL00000003CNKC",
"payload": {
"@context": {
"odrl": "http://www.w3.org/ns/odrl/2/"
},
"@id": "invalid-policy-2",
"policy": {
"policyId": "invalid-policy-5",
"createdOn": "2024-07-03T09:01:40.109000000Z",
"validUntil": "2024-07-04T00:00:00.000000000Z",
"permissions": [
{
"action": "use",
"constraint": {
"and": [
{
"leftOperand": "leftOperand",
"operator": {
"@id": "odrl:eq"
},
"rightOperand": "rightOperand"
}
]
}
}
]
}
}
}
Loading

0 comments on commit 8fa48d9

Please sign in to comment.