<commit_before>/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.xpack.security.audit;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.license.License;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.license.XPackLicenseState.Feature;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.MockLogAppender;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef;
import org.elasticsearch.xpack.core.security.authc.AuthenticationToken;
import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.AuthorizationInfo;
import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.security.transport.filter.IPFilter;
import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule;
import org.junit.Before;

import java.net.InetAddress;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.Collections.unmodifiableList;
import static org.elasticsearch.xpack.security.audit.logfile.LoggingAuditTrail.PRINCIPAL_ROLES_FIELD_NAME;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

public class AuditTrailServiceTests extends ESTestCase {
    private List<AuditTrail> auditTrails;
    private AuditTrailService service;

    private AuthenticationToken token;
    private TransportRequest request;
    private RestRequest restRequest;
    private XPackLicenseState licenseState;
    private boolean isAuditingAllowed;

    @Before
    public void init() throws Exception {
        List<AuditTrail> auditTrailsBuilder = new ArrayList<>();
        for (int i = 0; i < randomIntBetween(1, 4); i++) {
            auditTrailsBuilder.add(mock(AuditTrail.class));
        }
        auditTrails = unmodifiableList(auditTrailsBuilder);
        licenseState = mock(XPackLicenseState.class);
        service = new AuditTrailService(auditTrails, licenseState);
        isAuditingAllowed = randomBoolean();
        when(licenseState.isSecurityEnabled()).thenReturn(true);
        when(licenseState.checkFeature(Feature.SECURITY_AUDITING)).thenReturn(isAuditingAllowed);
        token = mock(AuthenticationToken.class);
        request = mock(TransportRequest.class);
        restRequest = mock(RestRequest.class);
    }

    public void testLogWhenLicenseProhibitsAuditing() throws Exception {
        MockLogAppender mockLogAppender = new MockLogAppender();
        mockLogAppender.start();
        Logger auditTrailServiceLogger = LogManager.getLogger(AuditTrailService.class);
        Loggers.addAppender(auditTrailServiceLogger, mockLogAppender);
        when(licenseState.getOperationMode()).thenReturn(randomFrom(License.OperationMode.values()));
        if (isAuditingAllowed) {
            mockLogAppender.addExpectation(new MockLogAppender.UnseenEventExpectation(
                    "audit disabled because of license",
                    AuditTrailService.class.getName(),
                    Level.WARN,
                    "Security auditing is DISABLED because the currently active license [" +
                            licenseState.getOperationMode() + "] does not permit it"
            ));
        } else {
            mockLogAppender.addExpectation(new MockLogAppender.SeenEventExpectation(
                    "audit disabled because of license",
                    AuditTrailService.class.getName(),
                    Level.WARN,
                    "Security auditing is DISABLED because the currently active license [" +
                            licenseState.getOperationMode() + "] does not permit it"
            ));
        }
        for (int i = 1; i <= randomIntBetween(2, 6); i++) {
            service.get();
        }
        mockLogAppender.assertAllExpectationsMatched();
        Loggers.removeAppender(auditTrailServiceLogger, mockLogAppender);
    }

    public void testNoLogRecentlyWhenLicenseProhibitsAuditing() throws Exception {
        MockLogAppender mockLogAppender = new MockLogAppender();
        mockLogAppender.start();
        Logger auditTrailServiceLogger = LogManager.getLogger(AuditTrailService.class);
        Loggers.addAppender(auditTrailServiceLogger, mockLogAppender);
        service.nextLogInstantAtomic.set(randomFrom(Instant.now().minus(Duration.ofMinutes(5)), Instant.now()));
        mockLogAppender.addExpectation(new MockLogAppender.UnseenEventExpectation(
                "audit disabled because of license",
                AuditTrailService.class.getName(),
                Level.WARN,
                "Security auditing is DISABLED because the currently active license [*] does not permit it"
        ));
        for (int i = 1; i <= randomIntBetween(2, 6); i++) {
            service.get();
        }
        mockLogAppender.assertAllExpectationsMatched();
        Loggers.removeAppender(auditTrailServiceLogger, mockLogAppender);<commit_msg>Fix test from 5414ad02edc2a14472eb3191<commit_after>/*
 * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
 * or more contributor license agreements. Licensed under the Elastic License;
 * you may not use this file except in compliance with the Elastic License.
 */
package org.elasticsearch.xpack.security.audit;

import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.common.logging.Loggers;
import org.elasticsearch.license.License;
import org.elasticsearch.license.XPackLicenseState;
import org.elasticsearch.license.XPackLicenseState.Feature;
import org.elasticsearch.rest.RestRequest;
import org.elasticsearch.test.ESTestCase;
import org.elasticsearch.test.MockLogAppender;
import org.elasticsearch.transport.TransportRequest;
import org.elasticsearch.xpack.core.security.authc.Authentication;
import org.elasticsearch.xpack.core.security.authc.Authentication.RealmRef;
import org.elasticsearch.xpack.core.security.authc.AuthenticationToken;
import org.elasticsearch.xpack.core.security.authz.AuthorizationEngine.AuthorizationInfo;
import org.elasticsearch.xpack.core.security.user.User;
import org.elasticsearch.xpack.security.transport.filter.IPFilter;
import org.elasticsearch.xpack.security.transport.filter.SecurityIpFilterRule;
import org.junit.Before;

import java.net.InetAddress;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import static java.util.Collections.unmodifiableList;
import static org.elasticsearch.xpack.security.audit.logfile.LoggingAuditTrail.PRINCIPAL_ROLES_FIELD_NAME;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

public class AuditTrailServiceTests extends ESTestCase {
    private List<AuditTrail> auditTrails;
    private AuditTrailService service;

    private AuthenticationToken token;
    private TransportRequest request;
    private RestRequest restRequest;
    private XPackLicenseState licenseState;
    private boolean isAuditingAllowed;

    @Before
    public void init() throws Exception {
        List<AuditTrail> auditTrailsBuilder = new ArrayList<>();
        for (int i = 0; i < randomIntBetween(1, 4); i++) {
            auditTrailsBuilder.add(mock(AuditTrail.class));
        }
        auditTrails = unmodifiableList(auditTrailsBuilder);
        licenseState = mock(XPackLicenseState.class);
        service = new AuditTrailService(auditTrails, licenseState);
        isAuditingAllowed = randomBoolean();
        when(licenseState.isSecurityEnabled()).thenReturn(true);
        when(licenseState.checkFeature(Feature.SECURITY_AUDITING)).thenReturn(isAuditingAllowed);
        token = mock(AuthenticationToken.class);
        request = mock(TransportRequest.class);
        restRequest = mock(RestRequest.class);
    }

    public void testLogWhenLicenseProhibitsAuditing() throws Exception {
        MockLogAppender mockLogAppender = new MockLogAppender();
        mockLogAppender.start();
        Logger auditTrailServiceLogger = LogManager.getLogger(AuditTrailService.class);
        Loggers.addAppender(auditTrailServiceLogger, mockLogAppender);
        when(licenseState.getOperationMode()).thenReturn(randomFrom(License.OperationMode.values()));
        if (isAuditingAllowed) {
            mockLogAppender.addExpectation(new MockLogAppender.UnseenEventExpectation(
                    "audit disabled because of license",
                    AuditTrailService.class.getName(),
                    Level.WARN,
                    "Auditing logging is DISABLED because the currently active license [" +
                            licenseState.getOperationMode() + "] does not permit it"
            ));
        } else {
            mockLogAppender.addExpectation(new MockLogAppender.SeenEventExpectation(
                    "audit disabled because of license",
                    AuditTrailService.class.getName(),
                    Level.WARN,
                    "Auditing logging is DISABLED because the currently active license [" +
                            licenseState.getOperationMode() + "] does not permit it"
            ));
        }
        for (int i = 1; i <= randomIntBetween(2, 6); i++) {
            service.get();
        }
        mockLogAppender.assertAllExpectationsMatched();
        Loggers.removeAppender(auditTrailServiceLogger, mockLogAppender);
    }

    public void testNoLogRecentlyWhenLicenseProhibitsAuditing() throws Exception {
        MockLogAppender mockLogAppender = new MockLogAppender();
        mockLogAppender.start();
        Logger auditTrailServiceLogger = LogManager.getLogger(AuditTrailService.class);
        Loggers.addAppender(auditTrailServiceLogger, mockLogAppender);
        service.nextLogInstantAtomic.set(randomFrom(Instant.now().minus(Duration.ofMinutes(5)), Instant.now()));
        mockLogAppender.addExpectation(new MockLogAppender.UnseenEventExpectation(
                "audit disabled because of license",
                AuditTrailService.class.getName(),
                Level.WARN,
                "Security auditing is DISABLED because the currently active license [*] does not permit it"
        ));
        for (int i = 1; i <= randomIntBetween(2, 6); i++) {
            service.get();
        }
        mockLogAppender.assertAllExpectationsMatched();
        Loggers.removeAppender(auditTrailServiceLogger, mockLogAppender);
{'fraction_non_alphanumeric': 0.08670778582283008, 'fraction_numerical': 0.0037543577366586215, 'mean_word_length': 3.5222312045270816, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 9, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6102307', 'n_tokens_mistral': 3009, 'n_tokens_neox': 2993, 'n_words': 592}