Commit 3b9f7f32 authored by Alinga Yeung's avatar Alinga Yeung
Browse files

Story 1869. Added unit test for ResetPassword. Added POST operation to ResetPassword.

parent c7536e6e
Loading
Loading
Loading
Loading
+12 −0
Original line number Diff line number Diff line
@@ -279,4 +279,16 @@ public interface UserPersistence<T extends Principal>
    void setPassword(HttpPrincipal userID, String oldPassword, String newPassword)
        throws UserNotFoundException, TransientException, AccessControlException;

    /**
     * Reset a user's password. The given user and authenticating user must match.
     *
     * @param userID
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    void resetPassword(HttpPrincipal userID, String newPassword)
        throws UserNotFoundException, TransientException, AccessControlException;

}
+46 −16
Original line number Diff line number Diff line
@@ -918,17 +918,7 @@ public class LdapUserDAO<T extends Principal> extends LdapDAO
        }
    }

    /**
     * Update a user's password. The given user and authenticating user must match.
     *
     * @param userID
     * @param oldPassword   current password.
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void setPassword(HttpPrincipal userID, String oldPassword, String newPassword)
    protected void updatePassword(HttpPrincipal userID, String oldPassword, String newPassword)
            throws UserNotFoundException, TransientException, AccessControlException
    {
        try
@@ -942,10 +932,19 @@ public class LdapUserDAO<T extends Principal> extends LdapDAO
            //conn.bind(bindRequest);

            LDAPConnection conn = this.getReadWriteConnection();

            PasswordModifyExtendedRequest passwordModifyRequest =
            PasswordModifyExtendedRequest passwordModifyRequest;
            if (StringUtil.hasText(oldPassword))
            {
                passwordModifyRequest =
                    new PasswordModifyExtendedRequest(
                        userDN.toNormalizedString(), new String(oldPassword), new String(newPassword));
            }
            else
            {
                passwordModifyRequest =
                    new PasswordModifyExtendedRequest(
                        userDN.toNormalizedString(), new String(newPassword));
            }                

            PasswordModifyExtendedResult passwordModifyResult = (PasswordModifyExtendedResult)
                    conn.processExtendedOperation(passwordModifyRequest);
@@ -959,6 +958,37 @@ public class LdapUserDAO<T extends Principal> extends LdapDAO
        }
    }
    
    /**
     * Update a user's password. The given user and authenticating user must match.
     *
     * @param userID
     * @param oldPassword   current password.
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void setPassword(HttpPrincipal userID, String oldPassword, String newPassword)
        throws UserNotFoundException, TransientException, AccessControlException
    {
        updatePassword(userID, oldPassword, newPassword);
    }

    /**
     * Reset a user's password. The given user and authenticating user must match.
     *
     * @param userID
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void resetPassword(HttpPrincipal userID, String newPassword)
        throws UserNotFoundException, TransientException, AccessControlException
    {
        updatePassword(userID, "", newPassword);
    }

    /**
     * Delete the user specified by userID from the active user tree.
     *
+36 −0
Original line number Diff line number Diff line
@@ -505,6 +505,42 @@ public class LdapUserPersistence<T extends Principal> extends LdapPersistence im
        }
    }

    /**
     * Reset a user's password. The given user and authenticating user must match.
     *
     * @param user
     * @param oldPassword   current password.
     * @param newPassword   new password.
     * @throws UserNotFoundException If the given user does not exist.
     * @throws TransientException   If an temporary, unexpected problem occurred.
     * @throws AccessControlException If the operation is not permitted.
     */
    public void resetPassword(HttpPrincipal userID, String newPassword)
            throws UserNotFoundException, TransientException, AccessControlException
    {
        Subject caller = AuthenticationUtil.getCurrentSubject();
        if ( !isMatch(caller, userID) )
            throw new AccessControlException("permission denied: target user does not match current user");
        
        LdapUserDAO<T> userDAO = null;
        LdapConnections conns = new LdapConnections(this);
        try
        {
            userDAO = new LdapUserDAO<T>(conns);
            User<T> user = getUser((T) userID);
            
            if (user != null)
            {
                // oldPassword is correct
                userDAO.resetPassword(userID, newPassword);
            }
        }
        finally
        {
            conns.releaseConnections();
        }
    }

    private boolean isMatch(Subject caller, User<T> user)
    {
        if (caller == null || AuthMethod.ANON.equals(AuthenticationUtil.getAuthMethod(caller)))
+16 −21
Original line number Diff line number Diff line
@@ -120,6 +120,7 @@ public class ResetPasswordServlet extends HttpServlet
        PluginFactory pluginFactory = new PluginFactory();
        userPersistence = pluginFactory.createUserPersistence();
    }
    
    /**
     * Handle a /ac GET operation. The subject provided is expected to be servops.
     *
@@ -139,11 +140,10 @@ public class ResetPasswordServlet extends HttpServlet
        try
        {
            final Subject subject = getSubject(request);
            final Set<HttpPrincipal> currentWebPrincipals =
                    subject.getPrincipals(HttpPrincipal.class);

            if (currentWebPrincipals.isEmpty())
            logInfo.setSubject(subject);
            if ((subject == null) || (subject.getPrincipals().isEmpty()))
            {
                logInfo.setMessage("Unauthorized subject");
                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            }
            else
@@ -152,10 +152,10 @@ public class ResetPasswordServlet extends HttpServlet
                {
                    public Object run() throws Exception
                    {
                        String email = request.getParameter("emailAddress");
                        if (StringUtil.hasText(email))
                        String emailAddress = request.getParameter("emailAddress");
                        if (StringUtil.hasText(emailAddress))
                        {
                            User<Principal> user = userPersistence.getUserByEmailAddress(email);
                            User<Principal> user = userPersistence.getUserByEmailAddress(emailAddress);
                            HttpPrincipal userID = (HttpPrincipal) user.getUserID();
                            URI scopeURI = new URI(ACScopeValidator.SCOPE);
                            int duration = 2; // hours
@@ -222,7 +222,7 @@ public class ResetPasswordServlet extends HttpServlet
     * @param request  The HTTP Request.
     * @param response The HTTP Response.
     * @throws IOException Any errors that are not expected.
     *
     */
    public void doPost(final HttpServletRequest request,
                       final HttpServletResponse response)
            throws IOException
@@ -248,26 +248,22 @@ public class ResetPasswordServlet extends HttpServlet
                        
                        Set<HttpPrincipal> pset = subject.getPrincipals(HttpPrincipal.class);
                        if (pset.isEmpty())
                        {
                            throw new IllegalStateException("no HttpPrincipal in subject");
                        }
                        
                        HttpPrincipal userID = pset.iterator().next();

                        String oldPassword = request.getParameter("old_password");
                        String newPassword = request.getParameter("new_password");
                        if (StringUtil.hasText(oldPassword))
                        {
                        String newPassword = request.getParameter("password");
                        if (StringUtil.hasText(newPassword))
                        {
                                userPersistence.setPassword(userID, oldPassword, newPassword);
                            }
                            else
                            {
                                throw new IllegalArgumentException("Missing new password");
                            }
                            userPersistence.resetPassword(userID, newPassword);
                        }
                        else
                        {
                            throw new IllegalArgumentException("Missing old password");
                            throw new IllegalArgumentException("Missing password");
                        }
                        
                        return null;
                    }
                });
@@ -299,7 +295,6 @@ public class ResetPasswordServlet extends HttpServlet
            log.info(logInfo.end());
        }
    }
    */

    /**
     * Get and augment the Subject. Tests can override this method.
+262 −0
Original line number Diff line number Diff line
/*
 ************************************************************************
 *******************  CANADIAN ASTRONOMY DATA CENTRE  *******************
 **************  CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES  **************
 *
 *  (c) 2015.                            (c) 2015.
 *  Government of Canada                 Gouvernement du Canada
 *  National Research Council            Conseil national de recherches
 *  Ottawa, Canada, K1A 0R6              Ottawa, Canada, K1A 0R6
 *  All rights reserved                  Tous droits réservés
 *
 *  NRC disclaims any warranties,        Le CNRC dénie toute garantie
 *  expressed, implied, or               énoncée, implicite ou légale,
 *  statutory, of any kind with          de quelque nature que ce
 *  respect to the software,             soit, concernant le logiciel,
 *  including without limitation         y compris sans restriction
 *  any warranty of merchantability      toute garantie de valeur
 *  or fitness for a particular          marchande ou de pertinence
 *  purpose. NRC shall not be            pour un usage particulier.
 *  liable in any event for any          Le CNRC ne pourra en aucun cas
 *  damages, whether direct or           être tenu responsable de tout
 *  indirect, special or general,        dommage, direct ou indirect,
 *  consequential or incidental,         particulier ou général,
 *  arising from the use of the          accessoire ou fortuit, résultant
 *  software.  Neither the name          de l'utilisation du logiciel. Ni
 *  of the National Research             le nom du Conseil National de
 *  Council of Canada nor the            Recherches du Canada ni les noms
 *  names of its contributors may        de ses  participants ne peuvent
 *  be used to endorse or promote        être utilisés pour approuver ou
 *  products derived from this           promouvoir les produits dérivés
 *  software without specific prior      de ce logiciel sans autorisation
 *  written permission.                  préalable et particulière
 *                                       par écrit.
 *
 *  This file is part of the             Ce fichier fait partie du projet
 *  OpenCADC project.                    OpenCADC.
 *
 *  OpenCADC is free software:           OpenCADC est un logiciel libre ;
 *  you can redistribute it and/or       vous pouvez le redistribuer ou le
 *  modify it under the terms of         modifier suivant les termes de
 *  the GNU Affero General Public        la “GNU Affero General Public
 *  License as published by the          License” telle que publiée
 *  Free Software Foundation,            par la Free Software Foundation
 *  either version 3 of the              : soit la version 3 de cette
 *  License, or (at your option)         licence, soit (à votre gré)
 *  any later version.                   toute version ultérieure.
 *
 *  OpenCADC is distributed in the       OpenCADC est distribué
 *  hope that it will be useful,         dans l’espoir qu’il vous
 *  but WITHOUT ANY WARRANTY;            sera utile, mais SANS AUCUNE
 *  without even the implied             GARANTIE : sans même la garantie
 *  warranty of MERCHANTABILITY          implicite de COMMERCIALISABILITÉ
 *  or FITNESS FOR A PARTICULAR          ni d’ADÉQUATION À UN OBJECTIF
 *  PURPOSE.  See the GNU Affero         PARTICULIER. Consultez la Licence
 *  General Public License for           Générale Publique GNU Affero
 *  more details.                        pour plus de détails.
 *
 *  You should have received             Vous devriez avoir reçu une
 *  a copy of the GNU Affero             copie de la Licence Générale
 *  General Public License along         Publique GNU Affero avec
 *  with OpenCADC.  If not, see          OpenCADC ; si ce n’est
 *  <http://www.gnu.org/licenses/>.      pas le cas, consultez :
 *                                       <http://www.gnu.org/licenses/>.
 *
 *
 ************************************************************************
 */

package ca.nrc.cadc.ac.server.web;

import ca.nrc.cadc.ac.User;
import ca.nrc.cadc.ac.server.ACScopeValidator;
import ca.nrc.cadc.ac.server.UserPersistence;
import ca.nrc.cadc.auth.DelegationToken;
import ca.nrc.cadc.auth.HttpPrincipal;
import ca.nrc.cadc.util.StringUtil;

import org.junit.Test;

import javax.security.auth.Subject;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.net.URI;
import java.security.Principal;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.TimeZone;

import static org.easymock.EasyMock.*;


public class ResetPasswordServletTest
{   
    public void testSubjectAndEmailAddress(final Subject subject, final String emailAddress, 
            int responseStatus) throws Exception
    {
        @SuppressWarnings("serial")
        final ResetPasswordServlet testSubject = new ResetPasswordServlet()
        {
            @Override
            Subject getSubject(final HttpServletRequest request)
            {
                return subject;
            }
        };
        
        final HttpServletRequest mockRequest =
                createMock(HttpServletRequest.class);
        final HttpServletResponse mockResponse =
                createMock(HttpServletResponse.class);
        
        expect(mockRequest.getPathInfo()).andReturn("users/CADCtest").once();
        expect(mockRequest.getMethod()).andReturn("POST").once();
        expect(mockRequest.getRemoteAddr()).andReturn("mysite.com").once();
        
        if (!StringUtil.hasText(emailAddress))
        {
            expect(mockRequest.getParameter("emailAddress")).andReturn(emailAddress).once();
        }
        
        mockResponse.setStatus(responseStatus);
        expectLastCall().once();
    
        replay(mockRequest, mockResponse);
    
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>()
        {
            @Override
            public Void run() throws Exception
            {
                testSubject.doGet(mockRequest, mockResponse);
                return null;
            }
        });
    
        verify(mockRequest, mockResponse);
    }
        
    @Test
    public void testGetDelegationTokenWithNullSubject() throws Exception
    {
        final Subject subject = null;
        testSubjectAndEmailAddress(subject, "testEmail@canada.ca", HttpServletResponse.SC_UNAUTHORIZED);
    }
        
    @Test
    public void testGetDelegationTokenWithEmptySubject() throws Exception
    {
        final Subject subject = new Subject();;
        testSubjectAndEmailAddress(subject, "email@canada.ca", HttpServletResponse.SC_UNAUTHORIZED);
    }
       
    @Test
    public void testGetDelegationTokenWithMissingEmailAddress() throws Exception
    {
        final Subject subject = new Subject();;
        subject.getPrincipals().add(new HttpPrincipal("CADCtest"));
        testSubjectAndEmailAddress(subject, "", HttpServletResponse.SC_BAD_REQUEST);
    }
    
    public void testGetDelegationToken(final boolean hasInternalServerError) throws Exception
    {
        DelegationToken dt = null;
        
        final String emailAddress = "email@canada.ca";
        HttpPrincipal userID = new HttpPrincipal("CADCtest");
        
        final UserPersistence<Principal> mockUserPersistence =
                createMock(UserPersistence.class);
        mockUserPersistence.getUserByEmailAddress(emailAddress);
        if (hasInternalServerError)
        {
            expectLastCall().andThrow(new RuntimeException());
        }
        else
        {
            URI scopeURI = new URI(ACScopeValidator.SCOPE);
            int duration = 2; // hours
            Calendar expiry = new GregorianCalendar(TimeZone.getTimeZone("UTC"));
            expiry.add(Calendar.HOUR, duration);
            dt = new DelegationToken(userID, scopeURI, expiry.getTime());
        }

        final Subject subject = new Subject();
        subject.getPrincipals().add(userID);
    
        @SuppressWarnings("serial")
        final ResetPasswordServlet testSubject = new ResetPasswordServlet()
        {
            @Override
            public void init(final ServletConfig config) throws ServletException
            {
                super.init();

                userPersistence = mockUserPersistence;
            }
           
            @Override
            Subject getSubject(final HttpServletRequest request)
            {
                return subject;
            }
        };
        
        final HttpServletRequest mockRequest =
                createMock(HttpServletRequest.class);
        final HttpServletResponse mockResponse =
                createMock(HttpServletResponse.class);
        
        expect(mockRequest.getPathInfo()).andReturn("users/CADCtest").once();
        expect(mockRequest.getMethod()).andReturn("POST").once();
        expect(mockRequest.getRemoteAddr()).andReturn("mysite.com").once();
        expect(mockRequest.getParameter("emailAddress")).andReturn(emailAddress).once();
    
        if (hasInternalServerError)
        {
            mockResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            expectLastCall().once();
        }
        else
        {
            String token = DelegationToken.format(dt);
            mockResponse.setContentType("text/plain");
            mockResponse.setContentLength(token.length());
            mockResponse.getWriter().write(token);
            expectLastCall().once();
        }
    
        replay(mockRequest, mockResponse, mockUserPersistence);
    
        Subject.doAs(subject, new PrivilegedExceptionAction<Void>()
        {
            @Override
            public Void run() throws Exception
            { 
                testSubject.doGet(mockRequest, mockResponse);
                return null;
            }
        });

        verify(mockRequest, mockResponse);
    }
    
    @Test
    public void testResetPasswordWithInternalServerError() throws Exception
    {
        boolean hasInternalServerError = true;
        testGetDelegationToken(hasInternalServerError);
    }
    
    @Test
    public void testResetPasswordHappyPath() throws Exception
    {
        boolean hasInternalServerError = false;
        testGetDelegationToken(hasInternalServerError);
    }        
}