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

Feature/786 add authorization to all endpoints #1129

Merged
merged 4 commits into from
Jun 28, 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ _**For better traceability add the corresponding GitHub issue number in each cha
- #1037 extended autocomplete api by contractAgreementId
- #985 Added function to save Contracts based on notification contractAgreementIds into the database
- #985 Added function to filter notifications for contractAgreementIds
- #786 Added authorization as admin for submodel api & registry api

### Added
- #832 added policymanagement list view, creator and editor
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public void registerDecentralRegistryPermissions() throws JsonProcessingExceptio
ObjectMapper mapper = new ObjectMapper();
mapper.registerModule(new JavaTimeModule());
mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

List<AcceptedPolicy> acceptedPolicy = buildAcceptedPolicies();
defaultAcceptedPoliciesProvider.addAcceptedPolicies(acceptedPolicy);
log.info("Successfully added permission to irs client lib provider: {}", mapper.writeValueAsString(acceptedPolicy));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,14 +21,11 @@
package org.eclipse.tractusx.traceability.common.config;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.eclipse.tractusx.traceability.common.properties.BpdmProperties;
import org.eclipse.tractusx.traceability.common.properties.EdcProperties;
import org.eclipse.tractusx.traceability.common.properties.FeignDefaultProperties;
Expand All @@ -40,22 +37,16 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.client.BufferingClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestFactory;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientProviderBuilder;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.RestTemplate;

import java.time.Duration;
import java.time.OffsetDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
Expand Down Expand Up @@ -83,7 +74,6 @@ public class RestTemplateConfiguration {
private final ClientRegistrationRepository clientRegistrationRepository;
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX");


/* RestTemplate used by trace x for the resolution of manufacturer names by BPN.*/
@Bean(BPDM_CLIENT_REST_TEMPLATE)
public RestTemplate bpdmClientRestTemplate(@Autowired BpdmProperties bpdmProperties) {
Expand Down Expand Up @@ -157,7 +147,6 @@ public RestTemplate irsRegularTemplate(@Autowired TraceabilityProperties traceab
/* RestTemplate used by trace x for the submodel server*/
@Bean(SUBMODEL_REST_TEMPLATE)
public RestTemplate submodelRestTemplate(@Autowired TraceabilityProperties traceabilityProperties, @Autowired FeignDefaultProperties feignDefaultProperties) {

return new RestTemplateBuilder()
.rootUri(traceabilityProperties.getSubmodelBase())
.setConnectTimeout(Duration.ofMillis(feignDefaultProperties.getConnectionTimeoutMillis()))
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ public class SecurityConfig {
"/callback/endpoint-data-reference",
"/internal/endpoint-data-reference",
"/actuator/**",
"/registry/reload",
"/submodel/**",
"/irs/job/callback"

};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,7 @@ public CreateNotificationContractResponse handle(CreateNotificationContractReque
throw new CreateNotificationContractException(e);
}


Optional<PolicyResponse> optionalPolicyResponse = policyService.getFirstPolicyMatchingApplicationConstraint();
EdcCreatePolicyDefinitionRequest edcCreatePolicyDefinitionRequest;
if (optionalPolicyResponse.isPresent()) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import assets.importpoc.ErrorResponse;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Tag(name = "Registry")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
@RequestMapping(path = "/registry", produces = "application/json")
@RequiredArgsConstructor
public class RegistryController {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import org.eclipse.tractusx.traceability.submodel.application.service.SubmodelService;
import org.eclipse.tractusx.traceability.submodel.domain.model.Submodel;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
Expand All @@ -45,6 +46,7 @@
@Slf4j
@RestController
@Tag(name = "Submodel")
@PreAuthorize("hasAnyRole('ROLE_ADMIN')")
@RequestMapping(path = "/submodel/data")
@RequiredArgsConstructor
public class SubmodelController {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,10 @@
package org.eclipse.tractusx.traceability.submodel.infrastructure.repository;

import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.eclipse.tractusx.traceability.submodel.domain.repository.SubmodelServerRepository;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor
public class SubmodelServerClientImpl implements SubmodelServerRepository {
Expand All @@ -32,6 +33,7 @@ public class SubmodelServerClientImpl implements SubmodelServerRepository {

@Override
public void saveSubmodel(String submodelId, String submodel) {
log.info(submodelId, "submodelId");
submodelClient.createSubmodel(submodelId, submodel);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,8 @@ traceability:
regularApiKey: testRegularKey
irsBase: "http://127.0.0.1"
irsPoliciesPath: "/irs/policies"
submodelBase: "http://localhost:${server.port}/api/submodel/data"
submodelBase: localhost:${server.port}/api/submodel/data

registry:
urlWithPath: "http://127.0.0.1"

Expand Down Expand Up @@ -91,7 +92,7 @@ digitalTwinRegistryClient:
shellLookupEndpoint: "" # required if type is "central", must contain the placeholder {assetIds}
feign:
submodelApi:
url: http://localhost:9998
url: ""
irsApi:
url: ""
adminApiKey: test
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@ public class RestitoConfig {
static {
STUB_SERVER = new StubServer(1025, 65000).run();
STUB_SERVER_PORT = STUB_SERVER.getPort();
System.out.println(STUB_SERVER_PORT + "PORT");
}

public static void clear() {
Expand All @@ -54,6 +55,7 @@ public void initialize(ConfigurableApplicationContext configurableApplicationCon
"spring.security.oauth2.client.provider.OKTA.token-uri=http://127.0.0.1:" + STUB_SERVER_PORT + OAUTH2_TOKEN_PATH,
"feign.bpnApi.url=http://127.0.0.1:" + STUB_SERVER_PORT,
"traceability.irsBase=http://127.0.0.1:" + STUB_SERVER_PORT,
"traceability.submodelBase=http://127.0.0.1:" + STUB_SERVER_PORT + "/api/submodel/data",
"feign.portalApi.url=http://127.0.0.1:" + STUB_SERVER_PORT,
"feign.irsApi.globalAssetId=testAssetId",
"feign.registryApi.url=http://127.0.0.1:" + STUB_SERVER_PORT,
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
/********************************************************************************
* Copyright (c) 2024 Contributors to the Eclipse Foundation
*
* See the NOTICE file(s) distributed with this work for additional
* information regarding copyright ownership.
*
* This program and the accompanying materials are made available under the
* terms of the Apache License, Version 2.0 which is available at
* https://www.apache.org/licenses/LICENSE-2.0.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*
* SPDX-License-Identifier: Apache-2.0
********************************************************************************/

package org.eclipse.tractusx.traceability.integration.common.support;

import org.glassfish.grizzly.http.util.HttpStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.xebialabs.restito.builder.stub.StubHttp.whenHttp;
import static com.xebialabs.restito.semantics.Action.status;
import static com.xebialabs.restito.semantics.Condition.startsWithUri;

@Component
public class SubmodelSupport {

@Autowired
RestitoProvider restitoProvider;

public void willCreateSubmodel() {

whenHttp(restitoProvider.stubServer()).match(startsWithUri("/api/submodel/data")
).then(
status(HttpStatus.CREATED_201)
);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,7 @@
import org.eclipse.tractusx.traceability.integration.common.support.DtrApiSupport;
import org.eclipse.tractusx.traceability.integration.common.support.EdcSupport;
import org.eclipse.tractusx.traceability.integration.common.support.IrsApiSupport;
import org.eclipse.tractusx.traceability.integration.common.support.SubmodelSupport;
import org.hamcrest.Matchers;
import org.jose4j.lang.JoseException;
import org.junit.jupiter.api.Test;
Expand Down Expand Up @@ -71,6 +72,9 @@ class ImportControllerIT extends IntegrationTestSpecification {
@Autowired
DtrApiSupport dtrApiSupport;

@Autowired
SubmodelSupport submodelSupport;

@Autowired
IrsApiSupport irsApiSupport;

Expand Down Expand Up @@ -130,6 +134,7 @@ void givenValidFileWithAsBuiltOnly_whenImportData_thenValidationShouldPass() thr
.multiPart(file)
.post("/api/assets/import")
.then()
.log().all()
.statusCode(200)
.extract().as(ImportResponse.class);

Expand Down Expand Up @@ -376,7 +381,7 @@ void givenInvalidAspect_whenImportData_thenValidationShouldNotPass() throws Jose
}

@Test
void givenValidFile_whenPublishData_thenStatusShouldChangeToInPublishedToCX() throws JoseException, InterruptedException, IOException {
void givenValidFile_whenPublishData_thenStatusShouldChangeToInPublishedToCX() throws JoseException, InterruptedException {
// given
String path = getClass().getResource("/testdata/importfiles/validImportFile.json").getFile();
File file = new File(path);
Expand All @@ -398,6 +403,7 @@ void givenValidFile_whenPublishData_thenStatusShouldChangeToInPublishedToCX() th
oAuth2ApiSupport.oauth2ApiReturnsTechnicalUserToken();
oAuth2ApiSupport.oauth2ApiReturnsDtrToken();
dtrApiSupport.dtrWillCreateShell();
submodelSupport.willCreateSubmodel();

// when
given()
Expand Down Expand Up @@ -444,6 +450,7 @@ void givenValidFile2_whenPublishData_thenStatusShouldChangeToPublishedToCx() thr
oAuth2ApiSupport.oauth2ApiReturnsTechnicalUserToken();
oAuth2ApiSupport.oauth2ApiReturnsDtrToken();
dtrApiSupport.dtrWillCreateShell();
submodelSupport.willCreateSubmodel();

// when
given()
Expand Down Expand Up @@ -492,6 +499,7 @@ void givenValidFile_whenPublishDataFailsOnDtr_thenStatusShouldChangeError() thro
oAuth2ApiSupport.oauth2ApiReturnsTechnicalUserToken();
oAuth2ApiSupport.oauth2ApiReturnsDtrToken();
dtrApiSupport.dtrWillFailToCreateShell();
submodelSupport.willCreateSubmodel();

// when
given()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,11 @@
package org.eclipse.tractusx.traceability.integration.submodel;

import io.restassured.http.ContentType;
import org.eclipse.tractusx.traceability.common.security.JwtRole;
import org.eclipse.tractusx.traceability.integration.IntegrationTestSpecification;
import org.eclipse.tractusx.traceability.submodel.infrastructure.model.SubmodelEntity;
import org.eclipse.tractusx.traceability.submodel.infrastructure.repository.JpaSubmodelRepository;
import org.jose4j.lang.JoseException;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;

Expand All @@ -37,7 +39,7 @@ class SubmodelControllerIT extends IntegrationTestSpecification {
JpaSubmodelRepository jpaSubmodelRepository;

@Test
void givenNoSubmodels_whenDeleteAll_thenDeleteSubmodelsFromDatabase() {
void givenNoSubmodels_whenDeleteAll_thenDeleteSubmodelsFromDatabase() throws JoseException {
// given
String submodelId = "UUID:Xa123123";
jpaSubmodelRepository.save(SubmodelEntity.builder()
Expand All @@ -51,6 +53,7 @@ void givenNoSubmodels_whenDeleteAll_thenDeleteSubmodelsFromDatabase() {
given()
.log().all()
.when()
.header(oAuth2Support.jwtAuthorization(JwtRole.ADMIN))
.delete("/api/submodel/data")
.then()
.log().all()
Expand All @@ -62,7 +65,7 @@ void givenNoSubmodels_whenDeleteAll_thenDeleteSubmodelsFromDatabase() {
}

@Test
void givenSubmodel_whenGetById_thenGetIt() {
void givenSubmodel_whenGetById_thenGetIt() throws JoseException {
// given
String submodelId = "UUID:Xa123123";
String payload = "Payload string";
Expand All @@ -75,6 +78,7 @@ void givenSubmodel_whenGetById_thenGetIt() {
String responseBody = given()
.log().all()
.when()
.header(oAuth2Support.jwtAuthorization(JwtRole.ADMIN))
.get("/api/submodel/data/" + submodelId)
.then()
.log().all()
Expand All @@ -87,28 +91,30 @@ void givenSubmodel_whenGetById_thenGetIt() {
}

@Test
void givenNoSubmodels_whenGetById_thenNotFound() {
void givenNoSubmodels_whenGetById_thenNotFound() throws JoseException {
// given
String submodelId = "UUID:Xa123123";

// when/then
given()
.log().all()
.when()
.header(oAuth2Support.jwtAuthorization(JwtRole.ADMIN))
.get("/api/submodel/data/" + submodelId)
.then()
.log().all()
.statusCode(404);
}

@Test
void givenSubmodel_whenSave_thenSaveIntoDatabase() {
void givenSubmodel_whenSave_thenSaveIntoDatabase() throws JoseException {
// given
String submodelId = "submodelId";
String requestContent = "test request";

// when
given()
.header(oAuth2Support.jwtAuthorization(JwtRole.ADMIN))
.contentType(ContentType.JSON)
.log().all()
.when()
Expand Down
Loading