Skip to content

Commit

Permalink
[#13] Throw error when allowed origins are not configured
Browse files Browse the repository at this point in the history
  • Loading branch information
blcham committed Nov 22, 2023
1 parent 42ff464 commit c653f33
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
11 changes: 10 additions & 1 deletion src/main/java/cz/cvut/kbss/study/config/SecurityConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -113,10 +113,19 @@ private static void configureAllowedOrigins(CorsConfiguration corsConfig, Config
final List<String> allowedOrigins = new ArrayList<>();
appUrlOrigin.ifPresent(allowedOrigins::add);
final String allowedOriginsConfig = config.getConfig(ConfigParam.CORS_ALLOWED_ORIGINS);
allowedOrigins.addAll(Arrays.asList(allowedOriginsConfig.split(",")));
Arrays.stream(allowedOriginsConfig.split(",")).filter(s -> !s.isBlank()).forEach(allowedOrigins::add);
if (!allowedOrigins.isEmpty()) {
corsConfig.setAllowedOrigins(allowedOrigins);
corsConfig.setAllowCredentials(true);
} else {
throw new RecordManagerException(String.format(
"The allowed origins are improperly configured as both"
+ " the '%s' and '%s' properties are empty. To permit requests from any origin,"
+ " configure it explicitly using '%s=*'.",
ConfigParam.APP_CONTEXT,
ConfigParam.CORS_ALLOWED_ORIGINS,
ConfigParam.CORS_ALLOWED_ORIGINS
));
}
}

Expand Down
12 changes: 12 additions & 0 deletions src/test/java/cz/cvut/kbss/study/config/SecurityConfigTest.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package cz.cvut.kbss.study.config;

import cz.cvut.kbss.study.exception.RecordManagerException;
import cz.cvut.kbss.study.service.ConfigReader;
import cz.cvut.kbss.study.util.ConfigParam;
import org.junit.jupiter.api.Test;
Expand All @@ -11,6 +12,7 @@
import static org.hamcrest.Matchers.hasItem;
import static org.hamcrest.Matchers.hasItems;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertThrows;

class SecurityConfigTest {

Expand Down Expand Up @@ -55,4 +57,14 @@ void createCorsConfigurationSupportsMultipleConfiguredAllowedOrigins() {
assertThat(result.getCorsConfiguration(new MockHttpServletRequest()).getAllowedOrigins(),
hasItems(originOne, originTwo, originThree));
}

@Test
void createCorsConfigurationThrowsRecordManagerExceptionWhenAppContextAndAllowedOriginsAreNotSet() {
environment.setProperty(ConfigParam.APP_CONTEXT.toString(), "");
environment.setProperty(ConfigParam.CORS_ALLOWED_ORIGINS.toString(),"");

assertThrows(RecordManagerException.class, () -> {
SecurityConfig.createCorsConfiguration(config);
});
}
}

0 comments on commit c653f33

Please sign in to comment.