/*
 * JOnAS: Java(TM) Open Application Server
 * Copyright (C) 1999 Bull S.A.
 * Contact: jonas-team@objectweb.org
 * 
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU Lesser General Public
 * License as published by the Free Software Foundation; either
 * version 2.1 of the License, or any later version.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public
 * License along with this library; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307
 * USA
 *
 * --------------------------------------------------------------------------
 * $Id$
 * --------------------------------------------------------------------------
 */

package org.objectweb.jonas.jtests.clients.security;


import java.rmi.RemoteException;
import java.util.Hashtable;
import java.util.Vector;

import org.ow2.jonas.lib.security.context.SecurityContext;
import org.ow2.jonas.lib.security.context.SecurityCurrent;

import org.objectweb.jonas.jtests.beans.secured.BaseS;
import org.objectweb.jonas.jtests.util.JTestCase;


/**
 * Security Management common tests for all type of beans (Entity/Session)
 *
 * @author Ph.Coq, Ph.Durieux
 *
 */

public abstract class A_AccessControl  extends JTestCase {

    protected static String PRINCIPAL1_NAME = "principal1";
    protected static String PRINCIPAL3_NAME = "principal3";
    protected static String ROLE1_NAME = "baserole1";
    protected static String ROLE2_NAME = "baserole2";

    protected static SecurityCurrent current = null;
    protected static SecurityContext principal1 = null;
    protected static SecurityContext principal2 = null;
    protected static SecurityContext principal3 = null;
    protected static SecurityContext principal4 = null;


    public A_AccessControl(String name) {
        super(name);
    }

    /**
     * init environment:
     * - load beans
     */
    protected void setUp() {
        super.setUp();
        if (current == null) {
            current = SecurityCurrent.getCurrent();
            principal1 = new SecurityContext("principal1", new String[] {"role1"});
            principal2 = new SecurityContext("principal2", new String[] {"role2"});
            String[] roles3 = new String[]{"role1", "role3"};
            principal3 = new SecurityContext(PRINCIPAL3_NAME, roles3);
            String[] roles4 = new String[]{"role2"};
            principal4 = new SecurityContext("principal4", roles4);
        }
    }

    public abstract BaseS getBaseS(String name) throws Exception;
    public abstract void removeBaseS(String name) throws Exception;

    /**
     * test getCallerPrincipal. 
     * The Principal must be propagated.
     */
    public void testGetCallerPrincipal() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("un");
        assertEquals(PRINCIPAL1_NAME, sl.getPrincipalName());
        sl.remove();
    }

    /**
     * test isCallerInRole.
     * principal1 = role1
     * principal2 = role2
     */
    public void testIsCallerInRole() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("deux");
        assertTrue(sl.isCallerInRole(ROLE1_NAME) == true);
        assertTrue(sl.isCallerInRole(ROLE2_NAME) == false);
        sl.remove();
    }

    /**
     * test testIsCallerInRoleRolesInContext.
     * principal1 = role1 (jonas-users.properties)
     * principal2 = role2 (jonas-users.properties)
     * principal3 = role1, role3 (role with security context)
     * principal4 = role2 (role with security context)
     */
    public void testIsCallerInRoleRolesInContext() throws Exception {
        current.setSecurityContext(principal3);
        BaseS sl = getBaseS("deuxbis");
        assertTrue(sl.isCallerInRole(ROLE1_NAME) == true);
        assertTrue(sl.isCallerInRole(ROLE2_NAME) == false);
        sl.remove();
    }

    /**
     * test basic method reject
     */
    public void testBasicMethodReject() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("trois");
        try {
            sl.simpleMethod(); 
            fail("should be rejected: not in the role");
        } catch (RemoteException e) {
        }
        sl.remove();
    }

    /**
     * test basic method reject
     */
    public void testBasicMethodRejectRolesInContext() throws Exception {
        current.setSecurityContext(principal3);
        BaseS sl = getBaseS("troisbis");
        try {
            sl.simpleMethod(); 
            fail("should be rejected: not in the role");
        } catch (RemoteException e) {
        }
        sl.remove();
    }


    /**
     * test basic method accept
     */
    public void testBasicMethodAccept() throws Exception {
        current.setSecurityContext(principal2);
        BaseS sl = getBaseS("quatre");
        sl.simpleMethod();
        sl.remove();
    }

    /**
     * test basic method accept
     */
    public void testBasicMethodAcceptRolesInContext() throws Exception {
        current.setSecurityContext(principal4);
        BaseS sl = getBaseS("quatrebis");
        sl.simpleMethod();
        sl.remove();
    }

    /**
     * test complex method reject
     */
    public void testComplexMethodReject() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("cinq");
        try {
            Hashtable ht = new Hashtable();
            ht.put("foo", new Vector(10));
            ht.put("bar", new Hashtable());
            Object[] o = {"bar", new Hashtable(), new Vector()};
            sl.complexMethod(ht, o);
            fail("should be rejected: not in the role");
        } catch (RemoteException e) {
        }
        sl.remove();
    }

    /**
     * test complex method reject
     */
    public void testComplexMethodRejectRolesInContext() throws Exception {
        current.setSecurityContext(principal3);
        BaseS sl = getBaseS("cinqbis");
        try {
            Hashtable ht = new Hashtable();
            ht.put("foo", new Vector(10));
            ht.put("bar", new Hashtable());
            Object[] o = {"bar", new Hashtable(), new Vector()};
            sl.complexMethod(ht, o);
            fail("should be rejected: not in the role");
        } catch (RemoteException e) {
        }
        sl.remove();
    }

    /**
     * test complex method accept
     */
    public void testComplexMethodAccept() throws Exception {
        current.setSecurityContext(principal2);
        BaseS sl = getBaseS("six");
        Hashtable ht = new Hashtable();
        ht.put("foo", new Vector(10));
        ht.put("bar", new Hashtable());
        Object[] o = {"bar", new Hashtable(), new Vector()};
        sl.complexMethod(ht, o);
        sl.remove();
    }

    /**
     * test complex method accept
     */
    public void testComplexMethodAcceptRolesInContext() throws Exception {
        current.setSecurityContext(principal4);
        BaseS sl = getBaseS("sixbis");
        Hashtable ht = new Hashtable();
        ht.put("foo", new Vector(10));
        ht.put("bar", new Hashtable());
        Object[] o = {"bar", new Hashtable(), new Vector()};
        sl.complexMethod(ht, o);
        sl.remove();
    }

    /**
     * test security-role-ref in DD
     * baserole -> role1
     */
    public void testSecurityRoleRef() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("sept");
        assertTrue(sl.isCallerInRole(ROLE1_NAME) == true);
        sl.remove();
    }

    /**
     * test security-role-ref in DD
     * baserole -> role1
     */
    public void testSecurityRoleRefRolesInContext() throws Exception {
        current.setSecurityContext(principal3);
        BaseS sl = getBaseS("septbis");
        assertTrue(sl.isCallerInRole(ROLE1_NAME) == true);
        sl.remove();
    }

    /**
     * test principal propagation from bean to bean
     */
    public void testBeanToBeanPropagation() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("sept");
        assertEquals(PRINCIPAL1_NAME, sl.getPrincipalNameOfAnotherBean());
        sl.remove();
    }

    /**
     * test principal propagation from bean to bean
     */
    public void testBeanToBeanPropagationRolesInContext() throws Exception {
        current.setSecurityContext(principal3);
        BaseS sl = getBaseS("sept");
        assertEquals(PRINCIPAL3_NAME, sl.getPrincipalNameOfAnotherBean());
        sl.remove();
    }

    /**
     * test principal propagation from bean to bean and access is denied
     */
    public void testRejectBeanToBeanAccess() throws Exception {
        current.setSecurityContext(principal2);
        BaseS sl = getBaseS("huit");
        try {
            sl.getPrincipalNameOfAnotherBean();
            fail("should be rejected: not in the role");
        } catch (RemoteException e) {
        } finally {
            // sl should have been discarded.
            removeBaseS("huit");
        }
    }

    /**
     * test principal propagation from bean to bean and access is denied
     */
    public void testRejectBeanToBeanAccessRolesInContext() throws Exception {
        current.setSecurityContext(principal4);
        BaseS sl = getBaseS("huitbis");
        try {
            sl.getPrincipalNameOfAnotherBean();
            fail("should be rejected: not in the role");
        } catch (RemoteException e) {
        } finally {
            // sl should have been discarded.
            removeBaseS("huitbis");
        }
    }

    /**
     * test accept access to a local method 
     * callAnotherMethod is called with role1 and call DerivedSF.anotheMethod with this role
     * return false if access to anotheMethod was denied
     * expected return is true
     */
    public void testLocalMethodAccept() throws Exception {
        current.setSecurityContext(principal1);
        BaseS sl = getBaseS("neuf");
        assertTrue(sl.callAnotherMethod() == true);
        sl.remove();
    }

    /**
     * test accept access to a local method 
     * callAnotherMethod is called with role1 and call DerivedSF.anotheMethod with this role
     * return false if access to anotheMethod was denied
     * expected return is true
     */
    public void testLocalMethodAcceptRolesInContext() throws Exception {
        current.setSecurityContext(principal3);
        BaseS sl = getBaseS("neufbis");
        assertTrue(sl.callAnotherMethod() == true);
        sl.remove();
    }

    /**
     * test reject access to a local method 
     * callAnotherMethod is called with role1 and call DerivedSF.anotheMethod with this role
     * return false if access to anotheMethod was denied
     * expected return is true
     */
    public void testLocalMethodReject() throws Exception {       
        current.setSecurityContext(principal2);
        BaseS sl = getBaseS("dix");
        assertTrue(sl.callAnotherMethod() == false);
        sl.remove();
    }

    /**
     * test reject access to a local method 
     * callAnotherMethod is called with role1 and call DerivedSF.anotheMethod with this role
     * return false if access to anotheMethod was denied
     * expected return is true
     */
    public void testLocalMethodRejectRolesInContext() throws Exception {       
        current.setSecurityContext(principal4);
        BaseS sl = getBaseS("dixbis");
        assertTrue(sl.callAnotherMethod() == false);
        sl.remove();
    }
    
    /**
     * test on an exluded method (excluded list)
     */
    public void testExcludedMethod() throws Exception {
        current.setSecurityContext(principal2);
        BaseS sl = getBaseS("excluded");
        try {
            sl.excludedMethod();
            fail("should be excluded");
        } catch (RemoteException e) {
        }
        sl.remove();
    }
    
    /**
     * test timeout
     */
    public void testTimeout() throws Exception {
        current.setSecurityContext(principal2);
        int duration = 5;
        BaseS sl = getBaseS("timed");
        try {
            int oldval = sl.getTimerCount();
            sl.setTimer(duration, 0, 0);
            sleep(2000);
            assertEquals("timer expired too quickly", oldval, sl.getTimerCount());
            sleep(4000);
            assertEquals("timer did not expired", oldval + 1, sl.getTimerCount());
        } finally {
            sl.remove();
        }
    }
}
