/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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 org.apache.struts2.interceptor;

import com.mockobjects.dynamic.Mock;
import org.apache.struts2.action.Action;
import org.apache.struts2.result.ActionChainResult;
import org.apache.struts2.ActionContext;
import org.apache.struts2.ActionInvocation;
import org.apache.struts2.SimpleAction;
import org.apache.struts2.TestBean;
import org.apache.struts2.XWorkTestCase;
import org.apache.struts2.util.ValueStack;
import org.apache.struts2.interceptor.parameter.StrutsParameterAuthorizer;
import org.apache.struts2.ognl.OgnlUtil;
import org.apache.struts2.util.ProxyService;
import org.mockito.ArgumentMatchers;
import org.mockito.Mockito;

import java.beans.IntrospectionException;
import java.util.*;

/**
 * Unit test for {@link ChainingInterceptor}.
 */
public class ChainingInterceptorTest extends XWorkTestCase {

    private ActionInvocation invocation;
    private ChainingInterceptor interceptor;
    private Mock mockInvocation;
    private ValueStack stack;

    public void testActionErrorsCanBeAddedAfterChain() throws Exception {
        SimpleAction action1 = new SimpleAction();
        SimpleAction action2 = new SimpleAction();
        action1.addActionError("foo");
        mockInvocation.matchAndReturn("getAction", action2);
        stack.push(action1);
        stack.push(action2);
        interceptor.setCopyErrors("true");
        interceptor.setCopyMessages("true");

        interceptor.intercept(invocation);

        assertEquals(action1.getActionErrors(), action2.getActionErrors());
        action2.addActionError("bar");
        assertEquals(1, action1.getActionErrors().size());
        assertEquals(2, action2.getActionErrors().size());
        assertTrue(action2.getActionErrors().contains("bar"));
    }

    public void testActionErrorsNotCopiedAfterChain() throws Exception {
        SimpleAction action1 = new SimpleAction();
        SimpleAction action2 = new SimpleAction();
        action1.addActionError("foo");
        mockInvocation.matchAndReturn("getAction", action2);
        stack.push(action1);
        stack.push(action2);

        interceptor.intercept(invocation);

        assertEquals(Collections.EMPTY_LIST, action2.getActionErrors());
        action2.addActionError("bar");
        assertEquals(1, action1.getActionErrors().size());
        assertEquals(1, action2.getActionErrors().size());
        assertTrue(action2.getActionErrors().contains("bar"));
        assertFalse(action2.getActionErrors().contains("foo"));
    }

    public void testPropertiesChained() throws Exception {
        TestBean bean = new TestBean();
        TestBeanAction action = new TestBeanAction();
        mockInvocation.matchAndReturn("getAction", action);
        bean.setBirth(new Date());
        bean.setName("foo");
        bean.setCount(1);
        stack.push(bean);
        stack.push(action);
        interceptor.setCopyErrors("true");
        interceptor.setCopyMessages("true");

        interceptor.intercept(invocation);

        assertEquals(bean.getBirth(), action.getBirth());
        assertEquals(bean.getName(), action.getName());
        assertEquals(bean.getCount(), action.getCount());
    }

    public void testExcludesPropertiesChained() throws Exception {
        TestBean bean = new TestBean();
        TestBeanAction action = new TestBeanAction();
        mockInvocation.matchAndReturn("getAction", action);
        bean.setBirth(new Date());
        bean.setName("foo");
        bean.setCount(1);
        stack.push(bean);
        stack.push(action);
        interceptor.setCopyErrors("true");
        interceptor.setCopyMessages("true");

        String excludes = "count";
        interceptor.setExcludes(excludes);

        interceptor.intercept(invocation);

        assertEquals(bean.getBirth(), action.getBirth());
        assertEquals(bean.getName(), action.getName());
        assertEquals(0, action.getCount());
        assertEquals(interceptor.getExcludes().iterator().next(), "count");
    }

    public void testTwoExcludesPropertiesChained() throws Exception {
        TestBean bean = new TestBean();
        TestBeanAction action = new TestBeanAction();
        mockInvocation.matchAndReturn("getAction", action);
        bean.setBirth(new Date());
        bean.setName("foo");
        bean.setCount(1);
        stack.push(bean);
        stack.push(action);

        String excludes = "name,count";
        interceptor.setExcludes(excludes);
        interceptor.intercept(invocation);
        assertEquals(bean.getBirth(), action.getBirth());
        assertNull(action.getName());
        assertEquals(0, action.getCount());
        assertTrue(interceptor.getExcludes().contains("count"));
        assertTrue(interceptor.getExcludes().contains("name"));
        assertEquals(2, interceptor.getExcludes().size());
    }

    public void testNullCompoundRootElementAllowsProcessToContinue() throws Exception {
        // we should not get NPE, but instead get a warning logged.
        stack.push(null);
        stack.push(null);
        stack.push(null);
        interceptor.intercept(invocation);
    }


    private StrutsParameterAuthorizer buildAuthorizer(boolean requireAnnotations, boolean transitionMode) {
        StrutsParameterAuthorizer authorizer = new StrutsParameterAuthorizer();
        authorizer.setOgnlUtil(container.getInstance(OgnlUtil.class));
        authorizer.setProxyService(container.getInstance(ProxyService.class));
        authorizer.setRequireAnnotations(String.valueOf(requireAnnotations));
        authorizer.setRequireAnnotationsTransitionMode(String.valueOf(transitionMode));
        return authorizer;
    }

    private void enableChainingEnforcement(boolean requireAnnotations, boolean transitionMode) {
        interceptor.setParameterAuthorizer(buildAuthorizer(requireAnnotations, transitionMode));
        interceptor.setRequireAnnotations("true");
    }

    public void testFlagOffCopiesUnannotatedProperty() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        UnannotatedChainingAction target = new UnannotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        interceptor.intercept(invocation);

        assertTrue("legacy chaining should copy the property when flag is off", target.getManagerApproved());
    }

    public void testFlagOnSkipsUnannotatedProperty() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        UnannotatedChainingAction target = new UnannotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        enableChainingEnforcement(true, false);
        interceptor.intercept(invocation);

        assertFalse("unannotated target property must NOT be copied when enforcement is on",
                target.getManagerApproved());
    }

    public void testFlagOnCopiesAnnotatedProperty() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        AnnotatedChainingAction target = new AnnotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        enableChainingEnforcement(true, false);
        interceptor.intercept(invocation);

        assertTrue("annotated target property should be copied when enforcement is on",
                target.getManagerApproved());
    }

    public void testTransitionModeCopiesNonNestedUnannotatedProperty() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        UnannotatedChainingAction target = new UnannotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        enableChainingEnforcement(true, true);
        interceptor.intercept(invocation);

        assertTrue("transition mode should copy depth-0 property without annotation",
                target.getManagerApproved());
    }

    public void testRequireAnnotationsFalseIsNoOp() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        UnannotatedChainingAction target = new UnannotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        interceptor.setParameterAuthorizer(buildAuthorizer(false, false));
        interceptor.setRequireAnnotations("true");
        interceptor.intercept(invocation);

        assertTrue("when global requireAnnotations is off, enforcement is a no-op",
                target.getManagerApproved());
    }

    public void testEnforcementStillFiltersWithIncludesConfigured() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        UnannotatedChainingAction target = new UnannotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        interceptor.setIncludes("managerApproved");
        enableChainingEnforcement(true, false);
        interceptor.intercept(invocation);

        assertFalse("unauthorized property must be excluded even when listed in includes",
                target.getManagerApproved());
    }

    public void testEnforcementResolvesProxiedTargetClass() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        UnannotatedChainingAction target = new UnannotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        ProxyService proxyService = Mockito.mock(ProxyService.class);
        Mockito.when(proxyService.isProxy(ArgumentMatchers.any())).thenReturn(true);
        Mockito.when(proxyService.ultimateTargetClass(ArgumentMatchers.any()))
                .thenReturn((Class) UnannotatedChainingAction.class);
        interceptor.setProxyService(proxyService);

        enableChainingEnforcement(true, false);
        interceptor.intercept(invocation);

        assertFalse("proxied unannotated target property must NOT be copied", target.getManagerApproved());
    }

    public void testFailsClosedWhenTargetCannotBeIntrospected() throws Exception {
        AnnotatedChainingAction source = new AnnotatedChainingAction();
        source.setManagerApproved(true);
        AnnotatedChainingAction target = new AnnotatedChainingAction();
        mockInvocation.matchAndReturn("getAction", target);
        stack.push(source);
        stack.push(target);

        // Introspection failure must fail closed: copy nothing, even for an annotated property.
        OgnlUtil ognlUtil = Mockito.mock(OgnlUtil.class);
        Mockito.when(ognlUtil.getBeanInfo(ArgumentMatchers.any(Class.class)))
                .thenThrow(new IntrospectionException("boom"));
        interceptor.setOgnlUtil(ognlUtil);

        enableChainingEnforcement(true, false);
        interceptor.intercept(invocation);

        assertFalse("nothing should be copied when the target cannot be introspected",
                target.getManagerApproved());
    }

    @Override
    protected void setUp() throws Exception {
        super.setUp();
        stack = ActionContext.getContext().getValueStack();
        mockInvocation = new Mock(ActionInvocation.class);
        mockInvocation.expectAndReturn("getStack", stack);
        mockInvocation.expectAndReturn("invoke", Action.SUCCESS);
        mockInvocation.expectAndReturn("getInvocationContext", ActionContext.of().bind());
        mockInvocation.expectAndReturn("getResult", new ActionChainResult());
        invocation = (ActionInvocation) mockInvocation.proxy();
        interceptor = new ChainingInterceptor();
        container.inject(interceptor);
    }


    private static class TestBeanAction extends TestBean implements Action {
        public String execute() throws Exception {
            return SUCCESS;
        }
    }
}
