diff --git a/src/main/java/edu/kit/datamanager/metastore2/configuration/ApplicationProperties.java b/src/main/java/edu/kit/datamanager/metastore2/configuration/ApplicationProperties.java index 31332a73..85d5686a 100644 --- a/src/main/java/edu/kit/datamanager/metastore2/configuration/ApplicationProperties.java +++ b/src/main/java/edu/kit/datamanager/metastore2/configuration/ApplicationProperties.java @@ -67,6 +67,9 @@ public class ApplicationProperties extends GenericApplicationProperties { @Value("${metastore.metadata.schemaRegistries: }") private List schemaRegistries; + @Value("${metastore.metadata.schemaRegistries: }") + private String postEnabledForRole; + @Value("${metastore.javers.scope:20}") private int maxJaversScope; diff --git a/src/main/java/edu/kit/datamanager/metastore2/configuration/WebSecurityConfig.java b/src/main/java/edu/kit/datamanager/metastore2/configuration/WebSecurityConfig.java index 7cbdb0a4..1558277f 100644 --- a/src/main/java/edu/kit/datamanager/metastore2/configuration/WebSecurityConfig.java +++ b/src/main/java/edu/kit/datamanager/metastore2/configuration/WebSecurityConfig.java @@ -68,18 +68,18 @@ public class WebSecurityConfig { private String allowedOriginPattern; private static final String[] AUTH_WHITELIST_SWAGGER_UI = { - // -- Swagger UI v2 - "/v2/api-docs", - "/swagger-resources", - "/swagger-resources/**", - "/configuration/ui", - "/configuration/security", - "/swagger-ui.html", - "/webjars/**", - // -- Swagger UI v3 (OpenAPI) - "/v3/api-docs/**", - "/swagger-ui/**" - // other public endpoints of your API may be appended to this array + // -- Swagger UI v2 + "/v2/api-docs", + "/swagger-resources", + "/swagger-resources/**", + "/configuration/ui", + "/configuration/security", + "/swagger-ui.html", + "/webjars/**", + // -- Swagger UI v3 (OpenAPI) + "/v3/api-docs/**", + "/swagger-ui/**" + // other public endpoints of your API may be appended to this array }; public WebSecurityConfig() { @@ -89,16 +89,27 @@ public WebSecurityConfig() { @Bean public SecurityFilterChain filterChain(HttpSecurity http) throws Exception { HttpSecurity httpSecurity = http.authorizeHttpRequests( - authorize -> authorize.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll(). - requestMatchers("/oaipmh").permitAll(). - requestMatchers("/static/**").permitAll(). - requestMatchers(AUTH_WHITELIST_SWAGGER_UI).permitAll(). - requestMatchers(EndpointRequest.to( - InfoEndpoint.class, - HealthEndpoint.class - )).permitAll(). - requestMatchers(EndpointRequest.toAnyEndpoint()).hasAnyRole("ANONYMOUS", "ADMIN", "ACTUATOR", "SERVICE_WRITE"). - requestMatchers("/**").authenticated()). + authorize -> { + authorize.requestMatchers(HttpMethod.OPTIONS, "/**").permitAll(). + requestMatchers("/oaipmh").permitAll(). + requestMatchers("/static/**").permitAll(). + requestMatchers(AUTH_WHITELIST_SWAGGER_UI).permitAll(). + requestMatchers(EndpointRequest.to( + InfoEndpoint.class, + HealthEndpoint.class + )).permitAll(); + logger.info("Post enabled for all groups!?"); + if (!applicationProperties.getPostEnabledForRole().isBlank()) { + logger.info("Post enabled for group '{}'!", applicationProperties.getPostEnabledForRole()); + authorize. + requestMatchers(HttpMethod.POST, "/api/v1/schemas/").hasAnyRole(applicationProperties.getPostEnabledForRole()). + requestMatchers(HttpMethod.POST, "/api/v2/schemas/").hasAnyRole(applicationProperties.getPostEnabledForRole()). + requestMatchers(HttpMethod.POST, "/api/v1/metadata/").hasAnyRole(applicationProperties.getPostEnabledForRole()). + requestMatchers(HttpMethod.POST, "/api/v2/metadata/").hasAnyRole(applicationProperties.getPostEnabledForRole()); + } + authorize.requestMatchers(EndpointRequest.toAnyEndpoint()).hasAnyRole("ANONYMOUS", "ADMIN", "ACTUATOR", "SERVICE_WRITE"). + requestMatchers("/**").authenticated(); + }). sessionManagement( session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS)); if (!enableCsrf) { diff --git a/src/test/java/edu/kit/datamanager/metastore2/test/CreateSchemaUtil.java b/src/test/java/edu/kit/datamanager/metastore2/test/CreateSchemaUtil.java index 23456317..8d0e75ab 100644 --- a/src/test/java/edu/kit/datamanager/metastore2/test/CreateSchemaUtil.java +++ b/src/test/java/edu/kit/datamanager/metastore2/test/CreateSchemaUtil.java @@ -38,164 +38,180 @@ import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** + * */ public class CreateSchemaUtil { - public final static String KIT_SCHEMA = "\n" - + "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + "\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SCC\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT_VERSION_2 = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SCC-DEM\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT_SMALL_CHANGE = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " DEM\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT_INVALID_1 = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SCC\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT_INVALID_2 = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SCC\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT_INVALID_3 = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SC\n" - + " \n" - + ""; - public final static String KIT_DOCUMENT_INVALID_4 = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SCC-TOLONG\n" - + " \n" - + ""; - - public final static String KIT_DOCUMENT_WRONG_NAMESPACE = "\n" - + " John Doe\n" - + " \n" - + " Scientific Computing Center\n" - + " SCC\n" - + " \n" - + ""; - public final static String XML_SCHEMA_V1 = "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " "; - public final static String XML_SCHEMA_V1_TYPO = "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " "; - public final static String XML_SCHEMA_V2 = "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " "; - public final static String XML_SCHEMA_V3 = "\n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " \n" - + " "; - public final static String XML_DOCUMENT_V1 = "\n" - + "\n" - + " Title of first version\n" - + ""; - public final static String XML_DOCUMENT_V2 = "\n" - + "\n" - + " Title of second version\n" - + " 2021-06-15\n" - + ""; + public final static String KIT_SCHEMA = """ + + + + + + \s + + + + + + \s + + + + + + \s + + + + + + + \s + + + + + + + + + + """; + public final static String KIT_DOCUMENT = """ + + John Doe + + Scientific Computing Center + SCC + + """; + public final static String KIT_DOCUMENT_VERSION_2 = """ + + John Doe + + Scientific Computing Center + SCC-DEM + + """; + public final static String KIT_DOCUMENT_SMALL_CHANGE = """ + + John Doe + + Scientific Computing Center + DEM + + """; + public final static String KIT_DOCUMENT_INVALID_1 = """ + + John Doe + + Scientific Computing Center + SCC + + """; + public final static String KIT_DOCUMENT_INVALID_2 = """ + + John Doe + + Scientific Computing Center + SCC + + """; + public final static String KIT_DOCUMENT_INVALID_3 = """ + + John Doe + + Scientific Computing Center + SC + + """; + public final static String KIT_DOCUMENT_INVALID_4 = """ + + John Doe + + Scientific Computing Center + SCC-TOLONG + + """; + + public final static String KIT_DOCUMENT_WRONG_NAMESPACE = """ + + John Doe + + Scientific Computing Center + SCC + + """; + public final static String XML_SCHEMA_V1 = """ + + + + + + + + + """; + public final static String XML_SCHEMA_V1_TYPO = """ + + + + + + + + + """; + public final static String XML_SCHEMA_V2 = """ + + + + + + + + + + """; + public final static String XML_SCHEMA_V3 = """ + + + + + + + + + + + """; + public final static String XML_DOCUMENT_V1 = """ + + + Title of first version + """; + public final static String XML_DOCUMENT_V2 = """ + + + Title of second version + 2021-06-15 + """; public final static String XML_DOCUMENT_V3 = "\n" + "\n" + " Title of third version\n" @@ -234,7 +250,7 @@ public static String ingestXmlSchemaRecord(MockMvc mockMvc, String schemaId, Str * @param schemaId * @param schemaContent * @param jwtSecret - * @param noUpdate Only ingest or do update also + * @param noUpdate Only ingest or do update also * @return * @throws Exception */ @@ -247,6 +263,23 @@ public static String ingestOrUpdateXmlSchemaRecord(MockMvc mockMvc, String schem addSimpleClaim("loginFailures", 0). addSimpleClaim("active", true). addSimpleClaim("locked", false).getCompactToken(jwtSecret); + return ingestOrUpdateXmlSchemaRecord(mockMvc, schemaId, schemaContent, update, userToken, expectedStatus); + } + + /** + * Update schema in MetaStore as user 'test_user'. If schema already exists + * and noUpdate is false update schema. + * + * @param mockMvc + * @param schemaId + * @param schemaContent + * @param jwtSecret + * @param noUpdate Only ingest or do update also + * @return + * @throws Exception + */ + public static String ingestOrUpdateXmlSchemaRecord(MockMvc mockMvc, String schemaId, String schemaContent, boolean update, String userToken, ResultMatcher expectedStatus) throws Exception { + String locationUri = null; MetadataSchemaRecord record = new MetadataSchemaRecord(); record.setSchemaId(schemaId); record.setType(MetadataSchemaRecord.SCHEMA_TYPE.XML); @@ -263,15 +296,15 @@ public static String ingestOrUpdateXmlSchemaRecord(MockMvc mockMvc, String schem schemaFile = new MockMultipartFile("schema", "schema.xsd", "application/xml", schemaContent.getBytes()); // Test if schema is already registered. MvcResult result = mockMvc.perform(get("/api/v1/schemas/" + schemaId). - header("Accept", MetadataSchemaRecord.METADATA_SCHEMA_RECORD_MEDIA_TYPE)). + header("Accept", MetadataSchemaRecord.METADATA_SCHEMA_RECORD_MEDIA_TYPE)). andDo(print()). andReturn(); if (result.getResponse().getStatus() != HttpStatus.OK.value()) { result = mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v1/schemas/"). - file(recordFile). - file(schemaFile). - header(HttpHeaders.AUTHORIZATION, "Bearer " + userToken)). + file(recordFile). + file(schemaFile). + header(HttpHeaders.AUTHORIZATION, "Bearer " + userToken)). andDo(print()).andExpect(expectedStatus).andReturn(); if (result.getResponse().getStatus() == HttpStatus.CREATED.value()) { locationUri = result.getResponse().getHeader("Location"); @@ -312,10 +345,12 @@ public static MvcResult ingestOrUpdateXmlMetadataDocument(MockMvc mockMvc, Strin addSimpleClaim("loginFailures", 0). addSimpleClaim("active", true). addSimpleClaim("locked", false).getCompactToken(jwtSecret); - // Test if metadataId is already registered. + return ingestOrUpdateXmlMetadataDocument(mockMvc, schemaId, version, metadataId, metadataDocument, update, userToken, expectedStatus); + } + public static MvcResult ingestOrUpdateXmlMetadataDocument(MockMvc mockMvc, String schemaId, Long version, String metadataId, String metadataDocument, boolean update, String userToken, ResultMatcher expectedStatus) throws Exception { + // Test if metadataId is already registered. MvcResult result = null; - MetadataRecord record = new MetadataRecord(); record.setId(metadataId); record.setSchema(ResourceIdentifier.factoryInternalResourceIdentifier(schemaId)); @@ -335,7 +370,7 @@ public static MvcResult ingestOrUpdateXmlMetadataDocument(MockMvc mockMvc, Strin metadataFile = new MockMultipartFile("document", "metadata.xml", "application/xml", metadataDocument.getBytes()); } result = mockMvc.perform(get("/api/v1/metadata/" + metadataId). - header("Accept", MetadataRecord.METADATA_RECORD_MEDIA_TYPE)). + header("Accept", MetadataRecord.METADATA_RECORD_MEDIA_TYPE)). andDo(print()). andReturn(); if (result.getResponse().getStatus() != HttpStatus.OK.value()) { @@ -405,7 +440,7 @@ public static String ingestXmlSchemaRecordV2(MockMvc mockMvc, String schemaId, S * @param schemaId * @param schemaContent * @param jwtSecret - * @param noUpdate Only ingest or do update also + * @param noUpdate Only ingest or do update also * @return * @throws Exception */ @@ -421,23 +456,24 @@ public static String ingestOrUpdateXmlSchemaRecordV2(MockMvc mockMvc, String sch * @param schemaId * @param schemaContent * @param jwtSecret - * @param noUpdate Only ingest or do update also + * @param noUpdate Only ingest or do update also * @return * @throws Exception */ public static String ingestOrUpdateJsonSchemaRecordV2(MockMvc mockMvc, String schemaId, String schemaContent, String jwtSecret, boolean update, ResultMatcher expectedStatus) throws Exception { return ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_JSON, schemaId, schemaContent, jwtSecret, update, expectedStatus); } + /** * Update schema in MetaStore as user 'test_user'. If schema already exists * and noUpdate is false update schema. * * @param mockMvc - * @param mediaType + * @param mediaType * @param schemaId * @param schemaContent * @param jwtSecret - * @param noUpdate Only ingest or do update also + * @param noUpdate Only ingest or do update also * @return * @throws Exception */ @@ -450,6 +486,24 @@ public static String ingestOrUpdateSchemaRecordV2(MockMvc mockMvc, MediaType med addSimpleClaim("loginFailures", 0). addSimpleClaim("active", true). addSimpleClaim("locked", false).getCompactToken(jwtSecret); + return ingestOrUpdateSchemaRecordV2(mockMvc, mediaType, schemaId, schemaContent, update, userToken, expectedStatus); + } + + /** + * Update schema in MetaStore as user 'test_user'. If schema already exists + * and noUpdate is false update schema. + * + * @param mockMvc + * @param mediaType + * @param schemaId + * @param schemaContent + * @param jwtSecret + * @param noUpdate Only ingest or do update also + * @return + * @throws Exception + */ + public static String ingestOrUpdateSchemaRecordV2(MockMvc mockMvc, MediaType mediaType, String schemaId, String schemaContent, boolean update, String userToken, ResultMatcher expectedStatus) throws Exception { + String locationUri = null; DataResource record; if (mediaType.toString().contains("xml")) { record = SchemaRegistryControllerTestV2.createDataResource4XmlSchema(schemaId); @@ -466,15 +520,15 @@ record = SchemaRegistryControllerTestV2.createDataResource4JsonSchema(schemaId); schemaFile = new MockMultipartFile("schema", "schema.xsd", "application/xml", schemaContent.getBytes()); // Test if schema is already registered. MvcResult result = mockMvc.perform(get("/api/v2/schemas/" + schemaId). - accept(DataResourceRecordUtil.DATA_RESOURCE_MEDIA_TYPE)). + accept(DataResourceRecordUtil.DATA_RESOURCE_MEDIA_TYPE)). andDo(print()). andReturn(); if (result.getResponse().getStatus() != HttpStatus.OK.value()) { result = mockMvc.perform(MockMvcRequestBuilders.multipart("/api/v2/schemas/"). - file(recordFile). - file(schemaFile). - header(HttpHeaders.AUTHORIZATION, "Bearer " + userToken)). + file(recordFile). + file(schemaFile). + header(HttpHeaders.AUTHORIZATION, "Bearer " + userToken)). andDo(print()).andExpect(expectedStatus).andReturn(); if (result.getResponse().getStatus() == HttpStatus.CREATED.value()) { locationUri = result.getResponse().getHeader("Location"); @@ -515,8 +569,13 @@ public static MvcResult ingestOrUpdateXmlMetadataDocumentV2(MockMvc mockMvc, Str addSimpleClaim("loginFailures", 0). addSimpleClaim("active", true). addSimpleClaim("locked", false).getCompactToken(jwtSecret); - // Test if metadataId is already registered. + return ingestOrUpdateXmlMetadataDocumentV2(mockMvc, schemaId, version, metadataId, metadataDocument, update, userToken, expectedStatus); + } + + public static MvcResult ingestOrUpdateXmlMetadataDocumentV2(MockMvc mockMvc, String schemaId, Long version, String metadataId, String metadataDocument, boolean update, String userToken, ResultMatcher expectedStatus) throws Exception { + + // Test if metadataId is already registered. MvcResult result = null; String versionAsString = null; if (version != null) { @@ -540,7 +599,7 @@ public static MvcResult ingestOrUpdateXmlMetadataDocumentV2(MockMvc mockMvc, Str metadataFile = new MockMultipartFile("document", "metadata.xml", "application/xml", metadataDocument.getBytes()); } result = mockMvc.perform(get("/api/v2/metadata/" + metadataId). - accept(DataResourceRecordUtil.DATA_RESOURCE_MEDIA_TYPE)). + accept(DataResourceRecordUtil.DATA_RESOURCE_MEDIA_TYPE)). andDo(print()). andReturn(); if (result.getResponse().getStatus() != HttpStatus.OK.value()) { diff --git a/src/test/java/edu/kit/datamanager/metastore2/test/MetadataControllerTestPostForRole.java b/src/test/java/edu/kit/datamanager/metastore2/test/MetadataControllerTestPostForRole.java new file mode 100644 index 00000000..3d4ab9d2 --- /dev/null +++ b/src/test/java/edu/kit/datamanager/metastore2/test/MetadataControllerTestPostForRole.java @@ -0,0 +1,278 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package edu.kit.datamanager.metastore2.test; + +import edu.kit.datamanager.entities.RepoServiceRole; +import edu.kit.datamanager.entities.RepoUserRole; +import edu.kit.datamanager.metastore2.configuration.ApplicationProperties; +import edu.kit.datamanager.metastore2.configuration.MetastoreConfiguration; +import edu.kit.datamanager.metastore2.dao.IDataRecordDao; +import edu.kit.datamanager.metastore2.dao.ILinkedMetadataRecordDao; +import edu.kit.datamanager.metastore2.dao.ISchemaRecordDao; +import edu.kit.datamanager.metastore2.dao.IUrl2PathDao; +import edu.kit.datamanager.repo.dao.IAllIdentifiersDao; +import edu.kit.datamanager.repo.dao.IContentInformationDao; +import edu.kit.datamanager.repo.dao.IDataResourceDao; +import edu.kit.datamanager.util.JwtBuilder; +import org.javers.core.Javers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; +import org.springframework.test.context.web.ServletTestExecutionListener; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; +import java.util.stream.Stream; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +/** + * + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) //RANDOM_PORT) +@EntityScan("edu.kit.datamanager") +@EnableJpaRepositories("edu.kit.datamanager") +@ComponentScan({"edu.kit.datamanager"}) +@AutoConfigureMockMvc +@TestExecutionListeners(listeners = {ServletTestExecutionListener.class, + DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + TransactionalTestExecutionListener.class, + WithSecurityContextTestExecutionListener.class}) +@ActiveProfiles("test") +@TestPropertySource(properties = {"server.port=41422"}) +@TestPropertySource(properties = {"spring.datasource.url=jdbc:h2:mem:db_md_postaccesswithaai;DB_CLOSE_DELAY=-1;MODE=LEGACY;NON_KEYWORDS=VALUE"}) +@TestPropertySource(properties = {"metastore.schema.schemaFolder=file:///tmp/metastore2/md/aai/postaccess/schema"}) +@TestPropertySource(properties = {"metastore.metadata.metadataFolder=file:///tmp/metastore2/md/aai/postaccess/metadata"}) +@TestPropertySource(properties = {"repo.auth.enabled=true"}) +@TestPropertySource(properties = {"metastore.postEnabledForRole=USER"}) +@TestPropertySource(properties = {"metastore.metadata.schemaRegistries="}) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class MetadataControllerTestPostForRole { + + private final static String TEMP_DIR_4_ALL = "/tmp/metastore2/md/aai/postaccess/"; + private final static String TEMP_DIR_4_SCHEMAS = TEMP_DIR_4_ALL + "schema/"; + private final static String TEMP_DIR_4_METADATA = TEMP_DIR_4_ALL + "metadata/"; + private static final String SCHEMA_ID = "my_dc_access_aai"; + private static final String INVALID_SCHEMA = "invalid_dc"; + + private String adminToken; + private String userToken; + private String otherUserToken; + private String guestToken; + private String serviceToken; + private String adminTokenWithRole; + private String userTokenWithRole; + private String otherUserTokenWithRole; + private String guestTokenWithRole; + private String adminTokenWithOtherRole; + private String userTokenWithOtherRole; + private String otherUserTokenWithOtherRole; + private String guestTokenWithOtherRole; + + private final String adminPrincipal = "admin"; + private final String userPrincipal = "user1"; + private final String otherUserPrincipal = "test_user"; + private final String guestPrincipal = "guest"; + private final String servicePrincipal = "any_service"; + + private final String ANONYMOUS_ID = "id_for_public_available_do"; + + private static Boolean alreadyInitialized = Boolean.FALSE; + + private MockMvc mockMvc; + @Autowired + private ApplicationProperties applicationProperties; + @Autowired + private WebApplicationContext context; + @Autowired + Javers javers = null; + @Autowired + private ILinkedMetadataRecordDao metadataRecordDao; + @Autowired + private IDataResourceDao dataResourceDao; + @Autowired + private IDataRecordDao dataRecordDao; + @Autowired + private ISchemaRecordDao schemaRecordDao; + @Autowired + private IContentInformationDao contentInformationDao; + @Autowired + private IAllIdentifiersDao allIdentifiersDao; + @Autowired + private IUrl2PathDao url2PathDao; + @Autowired + private MetastoreConfiguration metadataConfig; + @Rule + public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); + + @Before + public void setUp() throws Exception { + // setup mockMvc + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .apply(documentationConfiguration(this.restDocumentation).uris() + .withPort(41422)) + .build(); + + adminToken = createToken("adminWithoutRole", RepoUserRole.GUEST); + adminTokenWithOtherRole = createToken("adminWithOtherRole", RepoUserRole.CURATOR); + adminTokenWithRole = createToken("adminWithRole", RepoUserRole.ADMINISTRATOR, RepoUserRole.USER); + + userToken = createToken("userWithoutRole", RepoUserRole.GUEST); + userTokenWithOtherRole = createToken("userWithOtherRole", RepoUserRole.CURATOR); + userTokenWithRole = createToken("userWithRole", RepoUserRole.USER); + + otherUserToken = createToken("otherUserWithoutRole", RepoUserRole.GUEST); + otherUserTokenWithOtherRole = createToken("otherUserWithOtherRole", RepoUserRole.CURATOR); + otherUserTokenWithRole = createToken("otherUserWithRole", RepoUserRole.USER); + + guestToken = createToken("guestWithoutRole", RepoUserRole.GUEST); + guestTokenWithOtherRole = createToken("guestWithOtherRole", RepoUserRole.CURATOR); + guestTokenWithRole = createToken("guestWithRole", RepoUserRole.USER); + + + + serviceToken = edu.kit.datamanager.util.JwtBuilder.createServiceToken(servicePrincipal, RepoServiceRole.SERVICE_READ). + addSimpleClaim("email", "thomas.jejkal@kit.edu"). + addSimpleClaim("orcid", "0000-0003-2804-688X"). + addSimpleClaim("loginFailures", 0). + addSimpleClaim("active", true). + addSimpleClaim("locked", false).getCompactToken(applicationProperties.getJwtSecret()); + + if (!isInitialized()) { + System.out.println("------MetadataControllerAccessTestWithAAI-------------"); + System.out.println("------" + this.metadataConfig); + System.out.println("------------------------------------------------------"); + + contentInformationDao.deleteAll(); + dataResourceDao.deleteAll(); + metadataRecordDao.deleteAll(); + schemaRecordDao.deleteAll(); + dataRecordDao.deleteAll(); + allIdentifiersDao.deleteAll(); + url2PathDao.deleteAll(); + + try { + // Create schema only once. + try (Stream walk = Files.walk(Paths.get(URI.create("file://" + TEMP_DIR_4_SCHEMAS)))) { + walk.sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + Paths.get(TEMP_DIR_4_SCHEMAS).toFile().mkdir(); + Paths.get(TEMP_DIR_4_SCHEMAS + INVALID_SCHEMA).toFile().createNewFile(); + try (Stream walk = Files.walk(Paths.get(URI.create("file://" + TEMP_DIR_4_METADATA)))) { + walk.sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + Paths.get(TEMP_DIR_4_METADATA).toFile().mkdir(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + @Test + public void testPutSchemaWithoutRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, adminToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, userToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, otherUserToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, guestToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, serviceToken, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutSchemaWithOtherRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, adminTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, userTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, otherUserTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "notallowedtopost", "doesn't matter", false, guestTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + } + + @Test +public void testPutSchemaWithCorrectRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "allowedtopost1", CreateSchemaUtil.KIT_SCHEMA, false, adminTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "allowedtopost2", CreateSchemaUtil.KIT_SCHEMA, false, userTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "allowedtopost3", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "allowedtopost4", CreateSchemaUtil.KIT_SCHEMA, false, guestTokenWithRole, MockMvcResultMatchers.status().isCreated()); + } + + @Test + public void testPutMetadataWithoutRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "testputmetadatawithoutrole", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole1", CreateSchemaUtil.KIT_DOCUMENT,false, adminToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole2", CreateSchemaUtil.KIT_DOCUMENT,false, userToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole3", CreateSchemaUtil.KIT_DOCUMENT,false, otherUserToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole4", CreateSchemaUtil.KIT_DOCUMENT,false, guestToken, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutMetadataWithOtherRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "testputmetadatawithotherrole", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup1", CreateSchemaUtil.KIT_DOCUMENT,false, adminTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup2", CreateSchemaUtil.KIT_DOCUMENT,false, userTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup3", CreateSchemaUtil.KIT_DOCUMENT,false, otherUserTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup4", CreateSchemaUtil.KIT_DOCUMENT,false, guestTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutMetadataWithCorrectRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "testputmetadatawithcorrectrole1", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "testputmetadatawithcorrectrole2", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "testputmetadatawithcorrectrole3", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlSchemaRecord(mockMvc, "testputmetadatawithcorrectrole4", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithcorrectrole1", 1l, "usertokencorrectgroup1", CreateSchemaUtil.KIT_DOCUMENT,false, adminTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithcorrectrole2", 1l, "usertokencorrectgroup2", CreateSchemaUtil.KIT_DOCUMENT,false, userTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithcorrectrole3", 1l, "usertokencorrectgroup3", CreateSchemaUtil.KIT_DOCUMENT,false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocument(mockMvc, "testputmetadatawithcorrectrole4", 1l, "usertokencorrectgroup4", CreateSchemaUtil.KIT_DOCUMENT,false, guestTokenWithRole, MockMvcResultMatchers.status().isCreated()); + } + + public static synchronized boolean isInitialized() { + boolean returnValue = alreadyInitialized; + alreadyInitialized = Boolean.TRUE; + + return returnValue; + } + private String createToken(String principal, RepoUserRole... roles) { + return JwtBuilder.createUserToken(principal, roles). + addSimpleClaim("email", "thomas.jejkal@kit.edu"). + addSimpleClaim("orcid", "0000-0003-2804-688X"). + addSimpleClaim("loginFailures", 0). + addSimpleClaim("active", true). + addSimpleClaim("locked", false). + getCompactToken(applicationProperties.getJwtSecret()); + } +} diff --git a/src/test/java/edu/kit/datamanager/metastore2/test/MetadataControllerTestPostForRoleV2.java b/src/test/java/edu/kit/datamanager/metastore2/test/MetadataControllerTestPostForRoleV2.java new file mode 100644 index 00000000..4600f330 --- /dev/null +++ b/src/test/java/edu/kit/datamanager/metastore2/test/MetadataControllerTestPostForRoleV2.java @@ -0,0 +1,273 @@ +/* + * To change this license header, choose License Headers in Project Properties. + * To change this template file, choose Tools | Templates + * and open the template in the editor. + */ +package edu.kit.datamanager.metastore2.test; + +import edu.kit.datamanager.entities.RepoServiceRole; +import edu.kit.datamanager.entities.RepoUserRole; +import edu.kit.datamanager.metastore2.configuration.ApplicationProperties; +import edu.kit.datamanager.metastore2.configuration.MetastoreConfiguration; +import edu.kit.datamanager.metastore2.dao.IDataRecordDao; +import edu.kit.datamanager.metastore2.dao.ISchemaRecordDao; +import edu.kit.datamanager.metastore2.dao.IUrl2PathDao; +import edu.kit.datamanager.repo.dao.IAllIdentifiersDao; +import edu.kit.datamanager.repo.dao.IContentInformationDao; +import edu.kit.datamanager.repo.dao.IDataResourceDao; +import edu.kit.datamanager.util.JwtBuilder; +import org.javers.core.Javers; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.autoconfigure.domain.EntityScan; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.context.annotation.ComponentScan; +import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.http.MediaType; +import org.springframework.restdocs.JUnitRestDocumentation; +import org.springframework.security.test.context.support.WithSecurityContextTestExecutionListener; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ActiveProfiles; +import org.springframework.test.context.TestExecutionListeners; +import org.springframework.test.context.TestPropertySource; +import org.springframework.test.context.junit4.SpringRunner; +import org.springframework.test.context.support.DependencyInjectionTestExecutionListener; +import org.springframework.test.context.support.DirtiesContextTestExecutionListener; +import org.springframework.test.context.transaction.TransactionalTestExecutionListener; +import org.springframework.test.context.web.ServletTestExecutionListener; +import org.springframework.test.web.servlet.MockMvc; +import org.springframework.test.web.servlet.result.MockMvcResultMatchers; +import org.springframework.test.web.servlet.setup.MockMvcBuilders; +import org.springframework.web.context.WebApplicationContext; + +import java.io.File; +import java.io.IOException; +import java.net.URI; +import java.nio.file.Files; +import java.nio.file.Path; +import java.nio.file.Paths; +import java.util.Comparator; +import java.util.stream.Stream; + +import static org.springframework.restdocs.mockmvc.MockMvcRestDocumentation.documentationConfiguration; +import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity; + +/** + */ +@RunWith(SpringRunner.class) +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.DEFINED_PORT) //RANDOM_PORT) +@EntityScan("edu.kit.datamanager") +@EnableJpaRepositories("edu.kit.datamanager") +@ComponentScan({"edu.kit.datamanager"}) +@AutoConfigureMockMvc +@TestExecutionListeners(listeners = {ServletTestExecutionListener.class, + DependencyInjectionTestExecutionListener.class, + DirtiesContextTestExecutionListener.class, + TransactionalTestExecutionListener.class, + WithSecurityContextTestExecutionListener.class}) +@ActiveProfiles("test") +@TestPropertySource(properties = {"server.port=41442"}) +@TestPropertySource(properties = {"spring.datasource.url=jdbc:h2:mem:db_md_postaccesswithaai_v2;DB_CLOSE_DELAY=-1;MODE=LEGACY;NON_KEYWORDS=VALUE"}) +@TestPropertySource(properties = {"metastore.schema.schemaFolder=file:///tmp/metastore2/v2/md/aai/postaccess/schema"}) +@TestPropertySource(properties = {"metastore.metadata.metadataFolder=file:///tmp/metastore2/v2/md/aai/postaccess/metadata"}) +@TestPropertySource(properties = {"repo.auth.enabled=true"}) +@TestPropertySource(properties = {"metastore.postEnabledForRole=USER"}) +@TestPropertySource(properties = {"metastore.metadata.schemaRegistries="}) +@DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) +public class MetadataControllerTestPostForRoleV2 { + + private final static String TEMP_DIR_4_ALL = "/tmp/metastore2/v2/md/aai/postaccess/"; + private final static String TEMP_DIR_4_SCHEMAS = TEMP_DIR_4_ALL + "schema/"; + private final static String TEMP_DIR_4_METADATA = TEMP_DIR_4_ALL + "metadata/"; + private static final String SCHEMA_ID = "my_dc_access_aai"; + private static final String INVALID_SCHEMA = "invalid_dc"; + + private String adminToken; + private String userToken; + private String otherUserToken; + private String guestToken; + private String serviceToken; + private String adminTokenWithRole; + private String userTokenWithRole; + private String otherUserTokenWithRole; + private String guestTokenWithRole; + private String adminTokenWithOtherRole; + private String userTokenWithOtherRole; + private String otherUserTokenWithOtherRole; + private String guestTokenWithOtherRole; + + private final String adminPrincipal = "admin"; + private final String userPrincipal = "user1"; + private final String otherUserPrincipal = "test_user"; + private final String guestPrincipal = "guest"; + private final String servicePrincipal = "any_service"; + + private final String ANONYMOUS_ID = "id_for_public_available_do"; + + private static Boolean alreadyInitialized = Boolean.FALSE; + + private MockMvc mockMvc; + @Autowired + private ApplicationProperties applicationProperties; + @Autowired + private WebApplicationContext context; + @Autowired + Javers javers = null; + @Autowired + private IDataResourceDao dataResourceDao; + @Autowired + private IDataRecordDao dataRecordDao; + @Autowired + private ISchemaRecordDao schemaRecordDao; + @Autowired + private IContentInformationDao contentInformationDao; + @Autowired + private IAllIdentifiersDao allIdentifiersDao; + @Autowired + private IUrl2PathDao url2PathDao; + @Autowired + private MetastoreConfiguration metadataConfig; + @Rule + public JUnitRestDocumentation restDocumentation = new JUnitRestDocumentation(); + + @Before + public void setUp() throws Exception { + // setup mockMvc + this.mockMvc = MockMvcBuilders.webAppContextSetup(this.context) + .apply(springSecurity()) + .apply(documentationConfiguration(this.restDocumentation).uris() + .withPort(41442)) + .build(); + + adminToken = createToken("adminWithoutRole", RepoUserRole.GUEST); + adminTokenWithOtherRole = createToken("adminWithOtherRole", RepoUserRole.CURATOR); + adminTokenWithRole = createToken("adminWithRole", RepoUserRole.ADMINISTRATOR, RepoUserRole.USER); + + userToken = createToken("userWithoutRole", RepoUserRole.GUEST); + userTokenWithOtherRole = createToken("userWithOtherRole", RepoUserRole.CURATOR); + userTokenWithRole = createToken("userWithRole", RepoUserRole.USER); + + otherUserToken = createToken("otherUserWithoutRole", RepoUserRole.GUEST); + otherUserTokenWithOtherRole = createToken("otherUserWithOtherRole", RepoUserRole.CURATOR); + otherUserTokenWithRole = createToken("otherUserWithRole", RepoUserRole.USER); + + guestToken = createToken("guestWithoutRole", RepoUserRole.GUEST); + guestTokenWithOtherRole = createToken("guestWithOtherRole", RepoUserRole.CURATOR); + guestTokenWithRole = createToken("guestWithRole", RepoUserRole.USER); + + serviceToken = edu.kit.datamanager.util.JwtBuilder.createServiceToken(servicePrincipal, RepoServiceRole.SERVICE_READ). + addSimpleClaim("email", "thomas.jejkal@kit.edu"). + addSimpleClaim("orcid", "0000-0003-2804-688X"). + addSimpleClaim("loginFailures", 0). + addSimpleClaim("active", true). + addSimpleClaim("locked", false).getCompactToken(applicationProperties.getJwtSecret()); + + if (!isInitialized()) { + System.out.println("------MetadataControllerAccessTestWithAAIV2-------------"); + System.out.println("------" + this.metadataConfig); + System.out.println("------------------------------------------------------"); + + contentInformationDao.deleteAll(); + dataResourceDao.deleteAll(); + schemaRecordDao.deleteAll(); + dataRecordDao.deleteAll(); + allIdentifiersDao.deleteAll(); + url2PathDao.deleteAll(); + + try { + // Create schema only once. + try (Stream walk = Files.walk(Paths.get(URI.create("file://" + TEMP_DIR_4_SCHEMAS)))) { + walk.sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + Paths.get(TEMP_DIR_4_SCHEMAS).toFile().mkdir(); + Paths.get(TEMP_DIR_4_SCHEMAS + INVALID_SCHEMA).toFile().createNewFile(); + try (Stream walk = Files.walk(Paths.get(URI.create("file://" + TEMP_DIR_4_METADATA)))) { + walk.sorted(Comparator.reverseOrder()) + .map(Path::toFile) + .forEach(File::delete); + } + Paths.get(TEMP_DIR_4_METADATA).toFile().mkdir(); + } catch (IOException ex) { + ex.printStackTrace(); + } + } + } + + @Test + public void testPutSchemaWithoutRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, adminToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, userToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, otherUserToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, guestToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, serviceToken, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutSchemaWithOtherRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, adminTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, userTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, otherUserTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "notallowedtopost", "doesn't matter", false, guestTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutSchemaWithCorrectRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "allowedtopost1", CreateSchemaUtil.KIT_SCHEMA, false, adminTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "allowedtopost2", CreateSchemaUtil.KIT_SCHEMA, false, userTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "allowedtopost3", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "allowedtopost4", CreateSchemaUtil.KIT_SCHEMA, false, guestTokenWithRole, MockMvcResultMatchers.status().isCreated()); + } + + @Test + public void testPutMetadataWithoutRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "testputmetadatawithoutrole", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole1", CreateSchemaUtil.KIT_DOCUMENT,false, adminToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole2", CreateSchemaUtil.KIT_DOCUMENT,false, userToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole3", CreateSchemaUtil.KIT_DOCUMENT,false, otherUserToken, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithoutrole", 1l, "usertokenwithoutrole4", CreateSchemaUtil.KIT_DOCUMENT,false, guestToken, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutMetadataWithOtherRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "testputmetadatawithotherrole", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup1", CreateSchemaUtil.KIT_DOCUMENT,false, adminTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup2", CreateSchemaUtil.KIT_DOCUMENT,false, userTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup3", CreateSchemaUtil.KIT_DOCUMENT,false, otherUserTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithotherrole", 1l, "usertokenothergroup4", CreateSchemaUtil.KIT_DOCUMENT,false, guestTokenWithOtherRole, MockMvcResultMatchers.status().isForbidden()); + } + + @Test + public void testPutMetadataWithCorrectRole() throws Exception { + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "testputmetadatawithcorrectrole1", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "testputmetadatawithcorrectrole2", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "testputmetadatawithcorrectrole3", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateSchemaRecordV2(mockMvc, MediaType.APPLICATION_XML, "testputmetadatawithcorrectrole4", CreateSchemaUtil.KIT_SCHEMA, false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithcorrectrole1", 1l, "usertokencorrectgroup1", CreateSchemaUtil.KIT_DOCUMENT,false, adminTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithcorrectrole2", 1l, "usertokencorrectgroup2", CreateSchemaUtil.KIT_DOCUMENT,false, userTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithcorrectrole3", 1l, "usertokencorrectgroup3", CreateSchemaUtil.KIT_DOCUMENT,false, otherUserTokenWithRole, MockMvcResultMatchers.status().isCreated()); + CreateSchemaUtil.ingestOrUpdateXmlMetadataDocumentV2(mockMvc, "testputmetadatawithcorrectrole4", 1l, "usertokencorrectgroup4", CreateSchemaUtil.KIT_DOCUMENT,false, guestTokenWithRole, MockMvcResultMatchers.status().isCreated()); + } + + public static synchronized boolean isInitialized() { + boolean returnValue = alreadyInitialized; + alreadyInitialized = Boolean.TRUE; + + return returnValue; + } + + private String createToken(String principal, RepoUserRole... roles) { + return JwtBuilder.createUserToken(principal, roles). + addSimpleClaim("email", "thomas.jejkal@kit.edu"). + addSimpleClaim("orcid", "0000-0003-2804-688X"). + addSimpleClaim("loginFailures", 0). + addSimpleClaim("active", true). + addSimpleClaim("locked", false). + getCompactToken(applicationProperties.getJwtSecret()); + } +}