    1   /* Copyright 2004, 2005 Acegi Technology Pty Limited
    2    *
    3    * Licensed under the Apache License, Version 2.0 (the "License");
    4    * you may not use this file except in compliance with the License.
    5    * You may obtain a copy of the License at
    6    *
    7    *     http://www.apache.org/licenses/LICENSE-2.0
    8    *
    9    * Unless required by applicable law or agreed to in writing, software
    10   * distributed under the License is distributed on an "AS IS" BASIS,
    11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12   * See the License for the specific language governing permissions and
    13   * limitations under the License.
    14   */
    15
    16  package org.acegisecurity.adapters.catalina;
    17
    18  import junit.framework.TestCase;
    19
    20  import org.acegisecurity.GrantedAuthority;
    21  import org.acegisecurity.GrantedAuthorityImpl;
    22
    23  import org.acegisecurity.adapters.PrincipalAcegiUserToken;
    24
    25  import org.apache.catalina.LifecycleException;
    26
    27  import java.io.File;
    28
    29  import java.net.URL;
    30
    31  import java.security.Principal;
    32
    33
    34  /***
    35   * Tests {@link CatalinaAcegiUserRealm}.
    36   *
    37   * @author Ben Alex
    38   * @version $Id: CatalinaAcegiUserRealmTests.java,v 1.7 2005/11/25 00:26:30 benalex Exp $
    39   */
    40  public class CatalinaAcegiUserRealmTests extends TestCase {
    41      //~ Instance fields ========================================================
    42
    43      private final String ADAPTER_KEY = "my_key";
    44
    45      //~ Constructors ===========================================================
    46
    47      public CatalinaAcegiUserRealmTests() {
    48          super();
    49      }
    50
    51      public CatalinaAcegiUserRealmTests(String arg0) {
    52          super(arg0);
    53      }
    54
    55      //~ Methods ================================================================
    56
    57      public final void setUp() throws Exception {
    58          super.setUp();
    59      }
    60
    61      public static void main(String[] args) {
    62          junit.textui.TestRunner.run(CatalinaAcegiUserRealmTests.class);
    63      }
    64
    65      public void testAdapterAbortsIfAppContextDoesNotContainAnAuthenticationBean()
    66          throws Exception {
    67          try {
    68              CatalinaAcegiUserRealm adapter = makeAdapter(
    69                      "catalinaAdapterTest-invalid.xml");
    70              fail("Should have thrown IllegalArgumentException");
    71          } catch (IllegalArgumentException expected) {
    72              assertTrue(true);
    73          }
    74      }
    75
    76      public void testAdapterAbortsIfNoAppContextSpecified()
    77          throws Exception {
    78          CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    79
    80          adapter.setKey("KEY");
    81
    82          try {
    83              adapter.startForTest();
    84              fail("Should have thrown LifecycleException");
    85          } catch (LifecycleException expected) {
    86              assertEquals("appContextLocation must be defined",
    87                  expected.getMessage());
    88          }
    89
    90          adapter.setAppContextLocation("");
    91
    92          try {
    93              adapter.startForTest();
    94              fail("Should have thrown LifecycleException");
    95          } catch (LifecycleException expected) {
    96              assertEquals("appContextLocation must be defined",
    97                  expected.getMessage());
    98          }
    99      }
    100
    101     public void testAdapterAbortsIfNoKeySpecified() throws Exception {
    102         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    103
    104         adapter.setAppContextLocation("SOMETHING");
    105
    106         try {
    107             adapter.startForTest();
    108             fail("Should have thrown LifecycleException");
    109         } catch (LifecycleException expected) {
    110             assertEquals("key must be defined", expected.getMessage());
    111         }
    112
    113         adapter.setKey("");
    114
    115         try {
    116             adapter.startForTest();
    117             fail("Should have thrown LifecycleException");
    118         } catch (LifecycleException expected) {
    119             assertEquals("key must be defined", expected.getMessage());
    120         }
    121     }
    122
    123     public void testAdapterAbortsWithIncorrectApplicationContextLocation()
    124         throws Exception {
    125         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    126         adapter.setAppContextLocation("SOME_INVALID_PATH");
    127         adapter.setKey("KEY");
    128
    129         try {
    130             adapter.startForTest();
    131             fail("Should have thrown LifecycleException");
    132         } catch (LifecycleException expected) {
    133             assertTrue(expected.getMessage().startsWith("appContextLocation does not seem to exist in"));
    134         }
    135     }
    136
    137     public void testAdapterIdentifiesItself() throws Exception {
    138         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    139         assertTrue(adapter.getName().lastIndexOf("CatalinaSpringUserRealm") != -1);
    140     }
    141
    142     public void testAdapterStartsUpSuccess() throws Exception {
    143         CatalinaAcegiUserRealm adapter = makeAdapter(
    144                 "catalinaAdapterTest-valid.xml");
    145         assertTrue(true);
    146     }
    147
    148     public void testAuthenticateManyParamsReturnsNull() {
    149         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    150         assertEquals(null,
    151             adapter.authenticate(null, null, null, null, null, null, null, null));
    152     }
    153
    154     public void testAuthenticateX509ReturnsNull() {
    155         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    156         assertEquals(null, adapter.authenticate(null));
    157     }
    158
    159     public void testAuthenticationFailsForIncorrectPassword()
    160         throws Exception {
    161         CatalinaAcegiUserRealm adapter = makeAdapter(
    162                 "catalinaAdapterTest-valid.xml");
    163         assertEquals(null, adapter.authenticate("marissa", "kangaroo"));
    164     }
    165
    166     public void testAuthenticationFailsForIncorrectUserName()
    167         throws Exception {
    168         CatalinaAcegiUserRealm adapter = makeAdapter(
    169                 "catalinaAdapterTest-valid.xml");
    170         assertEquals(null, adapter.authenticate("melissa", "koala"));
    171     }
    172
    173     public void testAuthenticationUsingByteArrayForCredentials()
    174         throws Exception {
    175         CatalinaAcegiUserRealm adapter = makeAdapter(
    176                 "catalinaAdapterTest-valid.xml");
    177         byte[] credentials = {'k', 'o', 'a', 'l', 'a'};
    178         Principal result = adapter.authenticate("marissa", credentials);
    179
    180         if (!(result instanceof PrincipalAcegiUserToken)) {
    181             fail("Should have returned PrincipalAcegiUserToken");
    182         }
    183
    184         PrincipalAcegiUserToken castResult = (PrincipalAcegiUserToken) result;
    185         assertEquals("marissa", castResult.getPrincipal());
    186         assertEquals("koala", castResult.getCredentials());
    187         assertEquals("ROLE_TELLER",
    188             castResult.getAuthorities()[0].getAuthority());
    189         assertEquals("ROLE_SUPERVISOR",
    190             castResult.getAuthorities()[1].getAuthority());
    191         assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
    192     }
    193
    194     public void testAuthenticationUsingStringForCredentials()
    195         throws Exception {
    196         CatalinaAcegiUserRealm adapter = makeAdapter(
    197                 "catalinaAdapterTest-valid.xml");
    198         Principal result = adapter.authenticate("marissa", "koala");
    199
    200         if (!(result instanceof PrincipalAcegiUserToken)) {
    201             fail("Should have returned PrincipalAcegiUserToken");
    202         }
    203
    204         PrincipalAcegiUserToken castResult = (PrincipalAcegiUserToken) result;
    205         assertEquals("marissa", castResult.getPrincipal());
    206         assertEquals("koala", castResult.getCredentials());
    207         assertEquals("ROLE_TELLER",
    208             castResult.getAuthorities()[0].getAuthority());
    209         assertEquals("ROLE_SUPERVISOR",
    210             castResult.getAuthorities()[1].getAuthority());
    211         assertEquals(ADAPTER_KEY.hashCode(), castResult.getKeyHash());
    212     }
    213
    214     public void testAuthenticationWithNullPasswordHandledGracefully()
    215         throws Exception {
    216         CatalinaAcegiUserRealm adapter = makeAdapter(
    217                 "catalinaAdapterTest-valid.xml");
    218         assertEquals(null, adapter.authenticate("marissa", (String) null));
    219     }
    220
    221     public void testAuthenticationWithNullUserNameHandledGracefully()
    222         throws Exception {
    223         CatalinaAcegiUserRealm adapter = makeAdapter(
    224                 "catalinaAdapterTest-valid.xml");
    225         assertEquals(null, adapter.authenticate(null, "koala"));
    226     }
    227
    228     public void testGetPasswordReturnsNull() {
    229         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    230         assertEquals(null, adapter.getPassword(null));
    231     }
    232
    233     public void testGetPrincipalReturnsNull() {
    234         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    235         assertEquals(null, adapter.getPrincipal(null));
    236     }
    237
    238     public void testGetters() {
    239         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    240         adapter.setKey("KEY");
    241         assertEquals("KEY", adapter.getKey());
    242         adapter.setAppContextLocation("SOME_LOCATION");
    243         assertEquals("SOME_LOCATION", adapter.getAppContextLocation());
    244     }
    245
    246     public void testHasRoleWithANullPrincipalFails() {
    247         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    248         assertTrue(!adapter.hasRole(null, "ROLE_ONE"));
    249     }
    250
    251     public void testHasRoleWithAPrincipalTheAdapterDidNotCreateFails() {
    252         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    253         assertTrue(!adapter.hasRole(new Principal() {
    254                 public String getName() {
    255                     return "MockPrincipal";
    256                 }
    257             }, "ROLE_ONE"));
    258     }
    259
    260     public void testHasRoleWithPrincipalAcegiUserToken() {
    261         PrincipalAcegiUserToken token = new PrincipalAcegiUserToken("KEY",
    262                 "Test", "Password",
    263                 new GrantedAuthority[] {new GrantedAuthorityImpl("ROLE_ONE"), new GrantedAuthorityImpl(
    264                         "ROLE_TWO")}, null);
    265         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    266         assertTrue(adapter.hasRole(token, "ROLE_ONE"));
    267         assertTrue(adapter.hasRole(token, "ROLE_TWO"));
    268         assertTrue(!adapter.hasRole(token, "ROLE_WE_DO_NOT_HAVE"));
    269     }
    270
    271     private CatalinaAcegiUserRealm makeAdapter(String fileName)
    272         throws Exception {
    273         CatalinaAcegiUserRealm adapter = new CatalinaAcegiUserRealm();
    274
    275         URL url = Thread.currentThread().getContextClassLoader().getResource("org/acegisecurity/adapters/"
    276                 + fileName);
    277
    278         if (url == null) {
    279             throw new Exception("Could not find " + fileName
    280                 + " - cannot continue");
    281         }
    282
    283         File file = new File(url.getFile());
    284
    285         System.setProperty("catalina.base",
    286             file.getParentFile().getAbsolutePath());
    287         System.out.println("catalina.base set to: "
    288             + System.getProperty("catalina.base"));
    289         adapter.setAppContextLocation(fileName);
    290         adapter.setKey(ADAPTER_KEY);
    291         adapter.startForTest();
    292
    293         return adapter;
    294     }
    295 }