Skip to content

Commit

Permalink
chore(server): Audit api call (not GET) (#45)
Browse files Browse the repository at this point in the history
  • Loading branch information
nbrouand authored Apr 3, 2024
1 parent 43ecc91 commit 8f22315
Show file tree
Hide file tree
Showing 3 changed files with 162 additions and 1 deletion.
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@

package com.chutneytesting;

import com.chutneytesting.security.AuditHandler;
import com.chutneytesting.tools.ui.MyMixInForIgnoreType;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.databind.ObjectMapper;
Expand All @@ -28,9 +29,11 @@
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.Resource;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class WebConfiguration {
public class WebConfiguration implements WebMvcConfigurer {

@Bean
@Primary
Expand All @@ -50,6 +53,11 @@ WebServerFactoryCustomizer<AbstractServletWebServerFactory> embeddedServletConta
return this::setLocationForStaticAssets;
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new AuditHandler());
}

private void setLocationForStaticAssets(AbstractServletWebServerFactory container) {
File root = new File(resolvePathPrefix() + "ui/dist/chutney/"); // TODO use Path instead ?
if (root.exists() && root.isDirectory()) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
/*
* Copyright 2017-2023 Enedis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://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.
*
*/

package com.chutneytesting.security;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class AuditHandler implements HandlerInterceptor {
Logger logger = LoggerFactory.getLogger(AuditHandler.class);

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
if (!"GET".equals(request.getMethod())) {
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
if (authentication != null) {
logger.info("[{}] [{}] [{}]", authentication.getName(), request.getMethod(), request.getRequestURI());
}
}
return HandlerInterceptor.super.preHandle(request, response, handler);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,110 @@
/*
* Copyright 2017-2023 Enedis
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://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.
*
*/

package com.chutneytesting.security;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mockito;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;

@ExtendWith(OutputCaptureExtension.class)
public class AuditHandlerTest {

Authentication mockAuth = mock(Authentication.class);
static Logger auditHandlerLogger = ((LoggerContext) LoggerFactory.getILoggerFactory()).getLogger(AuditHandler.class);

@BeforeAll
public static void logLevelToInfo() {
auditHandlerLogger.setLevel(Level.INFO);
}

@AfterAll
public static void resetLogLevel() {
auditHandlerLogger.setLevel(Level.WARN);
}

@BeforeEach
public void setUp() {
Mockito.reset(mockAuth);
SecurityContextHolder.getContext().setAuthentication(null);
}

@Test
public void should_log_post(CapturedOutput output) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test/endpoint/42/entity");

MockHttpServletResponse response = new MockHttpServletResponse();
AuditHandler handler = new AuditHandler();

userAuthentified("user authentified");

boolean preHandled = handler.preHandle(request, response, null);

assertTrue(preHandled);
assertThat(output.getAll()).contains("[user authentified] [POST] [/test/endpoint/42/entity]");
}

@Test
public void should_not_log_if_no_auth(CapturedOutput output) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("POST", "/test");
MockHttpServletResponse response = new MockHttpServletResponse();
AuditHandler handler = new AuditHandler();

boolean preHandled = handler.preHandle(request, response, null);

assertTrue(preHandled);
assertThat(output.getAll()).isEmpty();
}

@Test
public void should_not_log_get_request(CapturedOutput output) throws Exception {
MockHttpServletRequest request = new MockHttpServletRequest("GET", "/test");
MockHttpServletResponse response = new MockHttpServletResponse();
AuditHandler handler = new AuditHandler();

userAuthentified("user");

boolean preHandled = handler.preHandle(request, response, null);

assertTrue(preHandled);
assertThat(output.getAll()).isEmpty();
}

private void userAuthentified(String username) {
when(mockAuth.getName()).thenReturn(username);
SecurityContextHolder.getContext().setAuthentication(mockAuth);
}

}

0 comments on commit 8f22315

Please sign in to comment.