private boolean checkRole(Authentication authentication, Object privilege, boolean logPermission) { String roleKey = getRoleKey(authentication); if (RoleConstant.SUPER_ADMIN.equals(roleKey)) { log(logPermission, Level.INFO, "access granted: privilege={}, role=SUPER-ADMIN, userKey={}", privilege, getUserKey()); return true; } if (!roleService.getRoles(TenantContextUtils.getRequiredTenantKeyValue(tenantContextHolder.getContext())) .containsKey(roleKey)) { log(logPermission, Level.ERROR, "access denied: privilege={}, role={}, userKey={} due to role is missing", privilege, roleKey, getUserKey()); throw new AccessDeniedException("Access is denied"); } return false; }
@POST @Consumes(MediaType.APPLICATION_JSON) @Produces(MediaType.APPLICATION_JSON) @Timed public Response handleRequestPost(SamlRequestDto samlRequestDto) { relayStateValidator.validate(samlRequestDto.getRelayState()); AuthnRequest authnRequest = stringSamlAuthnRequestTransformer.apply(samlRequestDto.getSamlRequest()); SamlValidationResponse signatureValidationResponse = authnRequestSignatureValidator.validate(authnRequest, SPSSODescriptor.DEFAULT_ELEMENT_NAME); protectiveMonitoringLogger.logAuthnRequest(authnRequest, Direction.INBOUND, signatureValidationResponse.isOK()); if (!signatureValidationResponse.isOK()) { SamlValidationSpecificationFailure failure = signatureValidationResponse.getSamlValidationSpecificationFailure(); throw new SamlTransformationErrorException(failure.getErrorMessage(), signatureValidationResponse.getCause(), Level.ERROR); } SamlAuthnRequestContainerDto samlAuthnRequestContainerDto = new SamlAuthnRequestContainerDto(samlRequestDto.getSamlRequest(), Optional.ofNullable(samlRequestDto.getRelayState()), samlRequestDto.getPrincipalIpAsSeenByFrontend()); SessionId sessionId = sessionProxy.createSession(samlAuthnRequestContainerDto); return Response.ok(sessionId).build(); }
private void log(Level level, String format, Object[] argArray) { switch (level) { case TRACE: logger.trace(format, argArray); break; case DEBUG: logger.debug(format, argArray); break; case INFO: logger.info(format, argArray); break; case WARN: logger.warn(format, argArray); break; case ERROR: logger.error(format, argArray); break; } }
@Test public void debug_format_argSupplier1() throws Exception { lambdaLogger.debug("debug format", () -> "arg1"); verify(lambdaLogger).doLog(eq(null), eq(Level.DEBUG), eq("debug format"), argSuppliersCaptor.capture(), eq(null)); Supplier[] suppliers = argSuppliersCaptor.getValue(); assertThat(suppliers.length).isEqualTo(1); assertThat(suppliers[0].get()).isEqualTo("arg1"); }
@Test(expected=SamlTransformationErrorException.class) public void handle_shouldNotifyPolicyWhenSamlStringCannotBeConvertedToAnElement() throws Exception { final SamlResponseDto samlResponse = new SamlResponseDto("Woooo!"); when(responseUnmarshaller.apply(samlResponse.getSamlResponse())).thenThrow(new SamlTransformationErrorException("not xml", Level.ERROR)); matchingServiceResponseTranslatorService.translate(samlResponse); // event sink logging is tested in SamlTransformationErrorExceptionMapperTest }
@Test public void error_marker_msgSupplier_throwable() throws Exception { lambdaLogger.error(testMarker, () -> "error message sup", testException); verify(lambdaLogger).doLog(eq(testMarker), eq(Level.ERROR), msgSupplierCaptor.capture(), eq(testException)); assertThat(msgSupplierCaptor.getValue().get()).isEqualTo("error message sup"); }
public void setDebugMode(boolean on) { if(on) { setLoggerLevel("com.paypal.butterfly", Level.DEBUG); } else { setLoggerLevel("com.paypal.butterfly", Level.INFO); } }
@Test public void testVerboseOn() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); logbackVerboseConfigurator.setDebugMode(true); Assert.assertTrue(loggerContext.getLogger("com.paypal.butterfly").getLevel() == ch.qos.logback.classic.Level.DEBUG); }
@Test public void testLoggerAsStringAndLogBackLevelAsInfo() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); logbackVerboseConfigurator.setLoggerLevel("com.paypal.butterfly.cli", Level.INFO); Assert.assertTrue(loggerContext.getLogger("com.paypal.butterfly.cli").getLevel() == ch.qos.logback.classic.Level.INFO); }
@Test public void testLoggerAsStringAndLogBackLevelAsInfoWithWrongPackage() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); logbackVerboseConfigurator.setLoggerLevel("com.paypal.butterfly.cli", Level.INFO); Assert.assertFalse(loggerContext.getLogger("com.paypal.butterfly.cli.test").getLevel() == ch.qos.logback.classic.Level.INFO); }
@Test public void testLoggerAsStringAndLogBackLevelAsDebug() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); logbackVerboseConfigurator.setLoggerLevel("com.paypal.butterfly.cli", Level.DEBUG); Assert.assertTrue(loggerContext.getLogger("com.paypal.butterfly.cli").getLevel() == ch.qos.logback.classic.Level.DEBUG); }
@Test public void info_marker_format_argSupplier1() throws Exception { lambdaLogger.info(testMarker, "info format", () -> "arg1"); verify(lambdaLogger).doLog(eq(testMarker), eq(Level.INFO), eq("info format"), argSuppliersCaptor.capture(), eq(null)); Supplier[] suppliers = argSuppliersCaptor.getValue(); assertThat(suppliers.length).isEqualTo(1); assertThat(suppliers[0].get()).isEqualTo("arg1"); }
@Test public void testLoggerAsClassAndLogBackLevelAsInfo() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); logbackVerboseConfigurator.setLoggerLevel(this.getClass(), Level.INFO); Assert.assertTrue(loggerContext.getLogger(this.getClass()).getLevel() == ch.qos.logback.classic.Level.INFO); }
@Test public void testLoggerAsClassAndLogBackLevelAsWarn() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); logbackVerboseConfigurator.setLoggerLevel(this.getClass(), Level.WARN); Assert.assertTrue(loggerContext.getLogger(this.getClass()).getLevel() == ch.qos.logback.classic.Level.WARN); }
@Test public void doLog_format_argSuppliers_enabled() throws Exception { when(underlyingLogger.isInfoEnabled(testMarker)).thenReturn(true); lambdaLogger.doLog(testMarker, Level.INFO, "message format", new Supplier<?>[] { () -> "hello", () -> "world" }, testException); verify(underlyingLogger, times(1)).log(testMarker, FQCN, Level.INFO.toInt(), "message format", new Object[] { "hello", "world" }, testException); }
@Test public void testLoggerAsClassAndLogBackLevelAsInvalid() { Assert.assertNotNull(logbackVerboseConfigurator); Assert.assertNotNull(loggerContext); try { logbackVerboseConfigurator.setLoggerLevel(this.getClass(), Level.TRACE); Assert.assertTrue(false); } catch (IllegalArgumentException ex) { Assert.assertTrue(ex.getMessage().equals("Unknown log level")); } }
@Test public void shouldHandleSamlContextExceptionCorrectly() throws Exception { final SamlContextException exception = new SamlContextException(UUID.randomUUID().toString(), "entityId", new SamlTransformationErrorException("error", Level.ERROR)); Response response = samlEngineExceptionMapper.toResponse(exception); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(responseEntity.isAudited()).isFalse(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML); checkLogLevel(exception.getLogLevel()); }
@Test public void goLog_format_arguments_enabled() throws Exception { when(underlyingLogger.isWarnEnabled(testMarker)).thenReturn(true); lambdaLogger.doLog(testMarker, Level.WARN, "message format", new Object[] { "arg1", "arg2" }, testException); verify(underlyingLogger, times(1)).log(testMarker, FQCN, Level.WARN.toInt(), "message format", new Object[] { "arg1", "arg2" }, testException); }
@Test public void doLog_format_argSuppliers_enabled_args_null() throws Exception { when(underlyingLogger.isInfoEnabled(testMarker)).thenReturn(true); lambdaLogger.doLog(testMarker, Level.INFO, "message format", null, testException); verify(underlyingLogger, times(1)).info(eq(testMarker), eq("message format"), eq(testException)); }
@Test public void error_msgSupplier_throwable() throws Exception { lambdaLogger.error(() -> "error message sup", testException); verify(lambdaLogger).doLog(eq(null), eq(Level.ERROR), msgSupplierCaptor.capture(), eq(testException)); assertThat(msgSupplierCaptor.getValue().get()).isEqualTo("error message sup"); }
@Test public void shouldCreateAuditedErrorResponseForRequestTooOldError() throws Exception { Response response = exceptionMapper.handleException(new SamlRequestTooOldException("error", new RuntimeException(), Level.DEBUG)); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML_REQUEST_TOO_OLD); }
@Override public void doLog(Marker marker, Level level, String format, Object[] arguments, Throwable t) { if (!LambdaLoggerUtils.isLogLevelEnabled(underlyingLogger, level, marker)) { return; } if (arguments == null) { logFormatted(marker, level, format, t); } else { FormattingTuple formattingTuple = MessageFormatter.arrayFormat(format, arguments, t); logFormatted(marker, level, formattingTuple.getMessage(), formattingTuple.getThrowable()); } }
@Test public void assertThatLogIsCreatedAtErrorLevelAndAuditIsSentToEventSink() throws Exception { when(context.get()).thenReturn(httpServletRequest); when(levelLoggerFactory.createLevelLogger(NoKeyConfiguredForEntityExceptionMapper.class)).thenReturn(levelLogger); NoKeyConfiguredForEntityExceptionMapper mapper = new NoKeyConfiguredForEntityExceptionMapper(context, levelLoggerFactory, eventSinkMessageSender); NoKeyConfiguredForEntityException exception = new NoKeyConfiguredForEntityException("entityId"); mapper.toResponse(exception); verify(levelLogger).log(Level.ERROR, exception); verify(eventSinkMessageSender).audit(any(NoKeyConfiguredForEntityException.class), any(UUID.class), any(SessionId.class)); }
@Test public void trace_msgSupplier_throwable() throws Exception { lambdaLogger.trace(() -> "trace message sup", testException); verify(lambdaLogger).doLog(eq(null), eq(Level.TRACE), msgSupplierCaptor.capture(), eq(testException)); assertThat(msgSupplierCaptor.getValue().get()).isEqualTo("trace message sup"); }
private static Level loggerLevel() { if (logger.isTraceEnabled()) { return TRACE; } else if (logger.isDebugEnabled()) { return DEBUG; } else if (logger.isInfoEnabled()) { return INFO; } else if (logger.isWarnEnabled()) { return WARN; } else { return ERROR; } }
@Test public void trace_marker_format_argSupplier1() throws Exception { lambdaLogger.trace(testMarker, "trace format", () -> "arg1"); verify(lambdaLogger).doLog(eq(testMarker), eq(Level.TRACE), eq("trace format"), argSuppliersCaptor.capture(), eq(null)); Supplier[] suppliers = argSuppliersCaptor.getValue(); assertThat(suppliers.length).isEqualTo(1); assertThat(suppliers[0].get()).isEqualTo("arg1"); }
@Test public void doLog_msgSupplier_enabled() throws Exception { when(underlyingLogger.isDebugEnabled(testMarker)).thenReturn(true); lambdaLogger.doLog(testMarker, Level.DEBUG, () -> "hello world!", testException); verify(underlyingLogger, times(1)).debug(eq(testMarker), eq("hello world!"), eq(testException)); }
@Override public Response toResponse(NoKeyConfiguredForEntityException exception) { levelLogger.log(Level.ERROR, exception); final Optional<SessionId> sessionId = Optional .ofNullable(context.get().getParameter(Urls.SharedUrls.SESSION_ID_PARAM)) .map(SessionId::new); eventSinkMessageSender.audit(exception, UUID.randomUUID(), sessionId.orElse(SessionId.NO_SESSION_CONTEXT_IN_ERROR)); return Response.status(Response.Status.BAD_REQUEST).build(); }
@Test public void trace_marker_msgSupplier_throwable() throws Exception { lambdaLogger.trace(testMarker, () -> "trace message sup", testException); verify(lambdaLogger).doLog(eq(testMarker), eq(Level.TRACE), msgSupplierCaptor.capture(), eq(testException)); assertThat(msgSupplierCaptor.getValue().get()).isEqualTo("trace message sup"); }
@Test public void run_shouldNotifySamlEngineAndLogErrorWhenMatchingServiceResponseIsNotProperlySigned() { when(executeAttributeQueryRequest.execute(sessionId, attributeQueryContainerDto)) .thenThrow(new SamlTransformationErrorException("Signature was not valid", Level.ERROR)); attributeQueryRequestRunnable.run(); final ArgumentCaptor<EventSinkHubEvent> loggedHubEvent = ArgumentCaptor.forClass(EventSinkHubEvent.class); verify(eventSinkProxy).logHubEvent(loggedHubEvent.capture()); assertThat(loggedHubEvent.getValue().getSessionId()).isEqualTo(sessionId.toString()); verify(hubMatchingServiceResponseReceiverProxy).notifyHubOfMatchingServiceRequestFailure(sessionId); verify(timeoutEvaluator, times(2)).hasAttributeQueryTimedOut(attributeQueryContainerDto); assertThat(loggedHubEvent.getValue().getDetails().get(message)).doesNotContain("Incorrect message provided by caller"); }
@Test public void shouldCreateAuditedErrorResponseForInvalidSaml() throws Exception { Response response = exceptionMapper.handleException(new TestSamlTransformationErrorException("error", new RuntimeException(), Level.DEBUG)); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode()); assertThat(responseEntity.isAudited()).isTrue(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML); }
@Test public void error_msgSupplier() throws Exception { lambdaLogger.error(() -> "error message sup"); verify(lambdaLogger).doLog(eq(null), eq(Level.ERROR), msgSupplierCaptor.capture(), eq(null)); assertThat(msgSupplierCaptor.getValue().get()).isEqualTo("error message sup"); }
@Test public void shouldHandleSamlTransformationErrorExceptionCorrectly() throws Exception { SamlTransformationErrorException exception = new SamlTransformationErrorException("error", new RuntimeException(), Level.DEBUG); final Response response = samlEngineExceptionMapper.toResponse(exception); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(responseEntity.isAudited()).isFalse(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_SAML); checkLogLevel(exception.getLogLevel()); }
@Test public void trace_marker_format_argSupplier1_argSupplier2() throws Exception { lambdaLogger.trace(testMarker, "trace format", () -> "arg1", () -> "arg2"); verify(lambdaLogger).doLog(eq(testMarker), eq(Level.TRACE), eq("trace format"), argSuppliersCaptor.capture(), eq(null)); Supplier[] suppliers = argSuppliersCaptor.getValue(); assertThat(suppliers.length).isEqualTo(2); assertThat(suppliers[0].get()).isEqualTo("arg1"); assertThat(suppliers[1].get()).isEqualTo("arg2"); }
/** * hard to check the logs provided by the interceptor when there's no error * however this unit test garantees the interceptor does not alter the reply * from the rest service. */ @Test public void testInterceptor() { List<ClientHttpRequestInterceptor> lInterceptors = new ArrayList<>(); //spring boot default log level is info lInterceptors.add(new LoggingRequestInterceptor(StandardCharsets.ISO_8859_1, 100, Level.ERROR)); SimpleClientHttpRequestFactory chrf = new SimpleClientHttpRequestFactory(); chrf.setOutputStreaming(false); rt.getRestTemplate().setRequestFactory(new InterceptingClientHttpRequestFactory( new BufferingClientHttpRequestFactory(chrf), lInterceptors )); ResponseEntity<String> resp = rt.getForEntity(MockedControllers.TEST_URL_GET, String.class); assertThat(resp.getBody()).isEqualTo(MockedControllers.TEST_RETURN_VALUE); }
@Test public void toResponse_shouldReturnUnauditedErrorStatus() throws Exception { HttpServletRequest httpServletRequest = mock(HttpServletRequest.class); when(httpServletRequest.getParameter(Urls.SharedUrls.SESSION_ID_PARAM)).thenReturn("42"); StateProcessingValidationExceptionMapper mapper = new StateProcessingValidationExceptionMapper(serviceInfo, eventSinkProxy); mapper.setHttpServletRequest(httpServletRequest); StateProcessingValidationException exception = new StateProcessingValidationException("error message", Level.ERROR); final Response response = mapper.toResponse(exception); assertThat(response.getEntity()).isNotNull(); ErrorStatusDto errorStatusDto = (ErrorStatusDto)response.getEntity(); assertThat(errorStatusDto.isAudited()).isEqualTo(false); assertThat(errorStatusDto.getExceptionType()).isEqualTo(ExceptionType.STATE_PROCESSING_VALIDATION); }
public SamlMessageDto createAttributeQueryContainer(T attributeQueryRequest, String matchingServiceEntityId) { String requestId = attributeQueryRequest.getId(); try { entityToEncryptForLocator.addEntityIdForRequestId(requestId, matchingServiceEntityId); return new SamlMessageDto(XmlUtils.writeToString(attributeQueryRequestTransformer.apply(attributeQueryRequest))); } catch (Exception e) { throw new UnableToGenerateSamlException("failed to create attribute query request", e, Level.ERROR); } finally { entityToEncryptForLocator.removeEntityIdForRequestId(requestId); } }
@Test public void shouldHandleUnableToGenerateSamlExceptionCorrectly() throws Exception { final UnableToGenerateSamlException exception = new UnableToGenerateSamlException("error", new RuntimeException(), Level.DEBUG); Response response = samlEngineExceptionMapper.toResponse(exception); ErrorStatusDto responseEntity = (ErrorStatusDto) response.getEntity(); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(responseEntity.isAudited()).isFalse(); assertThat(responseEntity.getExceptionType()).isEqualTo(ExceptionType.INVALID_INPUT); checkLogLevel(exception.getLogLevel()); }
@Test public void info_msgSupplier_throwable() throws Exception { lambdaLogger.info(() -> "info message sup", testException); verify(lambdaLogger).doLog(eq(null), eq(Level.INFO), msgSupplierCaptor.capture(), eq(testException)); assertThat(msgSupplierCaptor.getValue().get()).isEqualTo("info message sup"); }
@Test public void shouldReturnBadRequestForUnrecognizedException() { Response response = samlEngineExceptionMapper.toResponse(new RuntimeException("error")); assertThat(response.getStatus()).isEqualTo(Response.Status.BAD_REQUEST.getStatusCode()); assertThat(response.hasEntity()).isFalse(); checkLogLevel(Level.WARN); }