Commit 8ac8fa2b authored by Lukáš Chudíček's avatar Lukáš Chudíček
Browse files

feat: security & tests on ratings

parent bd5f671e
Loading
Loading
Loading
Loading
Loading
+0 −95
Original line number Diff line number Diff line
package cz.muni.fi.iamdb;

import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.Scopes;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@SpringBootApplication
public class RatingMicroserviceApp {

    private static final Logger log = LoggerFactory.getLogger(RatingMicroserviceApp.class);
    private static final String SECURITY_SCHEME_OAUTH2 = "MUNI";
    private static final String SECURITY_SCHEME_BEARER = "Bearer";

    public static void main(String[] args) {
        SpringApplication.run(RatingMicroserviceApp.class, args);
    }

    /**
     * Configure access restrictions to the API.
     * Introspection of opaque access token is configured, introspection endpoint is defined in application.yml.
     */
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // todo extract from properties
        final String RATING_POST_SCOPE = "SCOPE_test_1";
        final String RATING_GET_ALL_SCOPE = "SCOPE_test_2";
        final String RATING_GET_SPECIFIC_SCOPE = "SCOPE_test_3";
        final String RATING_PUT_SCOPE = "SCOPE_test_4";
        final String RATING_DELETE_SCOPE = "SCOPE_test_5";

        http
                .authorizeHttpRequests(x -> x
                        .requestMatchers(HttpMethod.POST, "/").hasAuthority(RATING_POST_SCOPE)
                        .requestMatchers(HttpMethod.GET, "/").hasAuthority(RATING_GET_ALL_SCOPE)
                        .requestMatchers(HttpMethod.GET, "/{id}").hasAuthority(RATING_GET_SPECIFIC_SCOPE)
                        .requestMatchers(HttpMethod.PUT, "/{id}").hasAuthority(RATING_PUT_SCOPE)
                        .requestMatchers(HttpMethod.DELETE, "/{id}").hasAuthority(RATING_DELETE_SCOPE)
                        // defensively deny all other requests
                        .anyRequest().denyAll()
                )
                .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults()))
        ;
        return http.build();
    }

    /**
     * Add security definitions to generated openapi.yaml.
     */
    @Bean
    public OpenApiCustomizer openAPICustomizer() {
        return openApi -> {
            log.info("adding security to OpenAPI description");
            openApi.getComponents()

                    .addSecuritySchemes(SECURITY_SCHEME_OAUTH2,
                            new SecurityScheme()
                                    .type(SecurityScheme.Type.OAUTH2)
                                    .description("get access token with OAuth 2 Authorization Code Grant")
                                    .flows(new OAuthFlows()
                                            .authorizationCode(new OAuthFlow()
                                                    .authorizationUrl("https://oidc.muni.cz/oidc/authorize")
                                                    .tokenUrl("https://oidc.muni.cz/oidc/token")
                                                    .scopes(new Scopes()
                                                            .addString("test_read", "reading things")
                                                            .addString("test_write", "creating things")
                                                            .addString("test_1", "deleting things")
                                                    )
                                            )
                                    )
                    )
                    .addSecuritySchemes(SECURITY_SCHEME_BEARER,
                            new SecurityScheme()
                                    .type(SecurityScheme.Type.HTTP)
                                    .scheme("bearer")
                                    .description("provide a valid access token")
                    )
            ;
        };
    }

    /**
     * Display a hint in the log.
     */
    @EventListener
    public void onApplicationEvent(ServletWebServerInitializedEvent event) {
        log.info("**************************");
        int port = event.getWebServer().getPort();
        log.info("visit http://localhost:{}/swagger-ui.html for UI", port);
        log.info("visit http://localhost:{}/openapi.yaml for OpenAPI document", port);
        log.info("**************************");
    }

}
+103 −0
Original line number Diff line number Diff line
package cz.muni.fi.iamdb.config;

import io.swagger.v3.oas.models.security.OAuthFlow;
import io.swagger.v3.oas.models.security.OAuthFlows;
import io.swagger.v3.oas.models.security.Scopes;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springdoc.core.customizers.OpenApiCustomizer;
import org.springframework.boot.web.servlet.context.ServletWebServerInitializedEvent;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.context.event.EventListener;
import org.springframework.http.HttpMethod;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@Profile("prod")
public class SecurityConfig {

    private static final Logger log = LoggerFactory.getLogger(SecurityConfig.class);
    private static final String SECURITY_SCHEME_OAUTH2 = "MUNI";
    private static final String SECURITY_SCHEME_BEARER = "Bearer";

    /**
     * Configure access restrictions to the API.
     * Introspection of opaque access token is configured, introspection endpoint is defined in application.yml.
     */
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
        // todo extract from properties
        final String RATING_POST_SCOPE = "SCOPE_test_1";
        final String RATING_GET_ALL_SCOPE = "SCOPE_test_2";
        final String RATING_GET_SPECIFIC_SCOPE = "SCOPE_test_3";
        final String RATING_PUT_SCOPE = "SCOPE_test_4";
        final String RATING_DELETE_SCOPE = "SCOPE_test_5";

        http
                .authorizeHttpRequests(x -> x
                        .requestMatchers(HttpMethod.POST, "/").hasAuthority(RATING_POST_SCOPE)
                        .requestMatchers(HttpMethod.GET, "/").hasAuthority(RATING_GET_ALL_SCOPE)
                        .requestMatchers(HttpMethod.GET, "/{id}").hasAuthority(RATING_GET_SPECIFIC_SCOPE)
                        .requestMatchers(HttpMethod.PUT, "/{id}").hasAuthority(RATING_PUT_SCOPE)
                        .requestMatchers(HttpMethod.DELETE, "/{id}").hasAuthority(RATING_DELETE_SCOPE)
                        // defensively deny all other requests
                        .anyRequest().denyAll()
                )
                .oauth2ResourceServer(oauth2 -> oauth2.opaqueToken(Customizer.withDefaults()))
        ;
        return http.build();
    }

    /**
     * Add security definitions to generated openapi.yaml.
     */
    @Bean
    public OpenApiCustomizer openAPICustomizer() {
        return openApi -> {
            log.info("adding security to OpenAPI description");
            openApi.getComponents()

                    .addSecuritySchemes(SECURITY_SCHEME_OAUTH2,
                            new SecurityScheme()
                                    .type(SecurityScheme.Type.OAUTH2)
                                    .description("get access token with OAuth 2 Authorization Code Grant")
                                    .flows(new OAuthFlows()
                                            .authorizationCode(new OAuthFlow()
                                                    .authorizationUrl("https://oidc.muni.cz/oidc/authorize")
                                                    .tokenUrl("https://oidc.muni.cz/oidc/token")
                                                    .scopes(new Scopes()
                                                            .addString("test_read", "reading things")
                                                            .addString("test_write", "creating things")
                                                            .addString("test_1", "deleting things")
                                                    )
                                            )
                                    )
                    )
                    .addSecuritySchemes(SECURITY_SCHEME_BEARER,
                            new SecurityScheme()
                                    .type(SecurityScheme.Type.HTTP)
                                    .scheme("bearer")
                                    .description("provide a valid access token")
                    )
            ;
        };
    }

    /**
     * Display a hint in the log.
     */
    @EventListener
    public void onApplicationEvent(ServletWebServerInitializedEvent event) {
        log.info("**************************");
        int port = event.getWebServer().getPort();
        log.info("visit http://localhost:{}/swagger-ui.html for UI", port);
        log.info("visit http://localhost:{}/openapi.yaml for OpenAPI document", port);
        log.info("**************************");
    }

}
+3 −1
Original line number Diff line number Diff line
@@ -7,6 +7,8 @@ server:
    include-message: always

spring:
  profiles:
    active: prod
  # # secrets should not be stored here
#  jpa:
#    open-in-view: false
+26 −0
Original line number Diff line number Diff line
package cz.muni.fi.iamdb.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
@Profile("test")
public class SecurityConfig {
    /**
     * Configure access restrictions to the API.
     * Introspection of opaque access token is configured, introspection endpoint is defined in application.yml.
     */
    @Bean
    SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {

        http
                .authorizeHttpRequests(x -> x
                        .anyRequest().permitAll()
                )
        ;
        return http.build();
    }
}
+38 −38
Original line number Diff line number Diff line
//package cz.muni.fi.iamdb.rest;
//
//import cz.muni.fi.iamdb.data.model.Rating;
//import cz.muni.fi.iamdb.data.repository.RatingRepository;
//import org.junit.jupiter.api.Test;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
//import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
//import org.springframework.test.context.ActiveProfiles;
//
//import java.util.UUID;
//
//import static org.assertj.core.api.Assertions.assertThat;
//
//@DataJpaTest
//@ActiveProfiles("test")
//public class RatingRepositoryIT {
//
//    @Autowired
//    private TestEntityManager entityManager;
//
//    @Autowired
//    private RatingRepository ratingRepository;
//
//    @Test
//    void testCreateAndFindById() {
//        UUID movieId = UUID.randomUUID();
//        UUID userId = UUID.randomUUID();
//        Rating newRating = new Rating(null, movieId, userId, 9.5, "Excellent movie");
//        newRating = entityManager.persistFlushFind(newRating);
//
//        Rating foundRating = ratingRepository.findById(newRating.getId()).orElse(null);
//
//        assertThat(foundRating).isNotNull();
//        assertThat(foundRating.getScore()).isEqualTo(9.5);
//        assertThat(foundRating.getReview()).isEqualTo("Excellent movie");
//    }
//}
package cz.muni.fi.iamdb.rest;

import cz.muni.fi.iamdb.data.model.Rating;
import cz.muni.fi.iamdb.data.repository.RatingRepository;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest;
import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager;
import org.springframework.test.context.ActiveProfiles;

import java.util.UUID;

import static org.assertj.core.api.Assertions.assertThat;

@DataJpaTest
@ActiveProfiles("test")
public class RatingRepositoryIT {

    @Autowired
    private TestEntityManager entityManager;

    @Autowired
    private RatingRepository ratingRepository;

    @Test
    void testCreateAndFindById() {
        UUID movieId = UUID.randomUUID();
        UUID userId = UUID.randomUUID();
        Rating newRating = new Rating(null, movieId, userId, 9.5, "Excellent movie");
        newRating = entityManager.persistFlushFind(newRating);

        Rating foundRating = ratingRepository.findById(newRating.getId()).orElse(null);

        assertThat(foundRating).isNotNull();
        assertThat(foundRating.getScore()).isEqualTo(9.5);
        assertThat(foundRating.getReview()).isEqualTo("Excellent movie");
    }
}
Loading