Search in sources :

Example 16 with Log

use of org.apache.commons.logging.Log in project alfresco-remote-api by Alfresco.

the class BaseNTLMAuthenticationFilter method processType3.

/**
 * Process a type 3 NTLM message
 *
 * @param type3Msg Type3NTLMMessage
 * @param req HttpServletRequest
 * @param res HttpServletResponse
 *
 * @exception IOException
 * @exception ServletException
 */
protected boolean processType3(Type3NTLMMessage type3Msg, ServletContext context, HttpServletRequest req, HttpServletResponse res) throws IOException, ServletException {
    Log logger = getLogger();
    if (logger.isDebugEnabled())
        logger.debug("Received type3 " + type3Msg);
    // Get the existing NTLM details
    NTLMLogonDetails ntlmDetails = null;
    SessionUser user = null;
    user = getSessionUser(context, req, res, true);
    HttpSession session = req.getSession();
    ntlmDetails = (NTLMLogonDetails) session.getAttribute(NTLM_AUTH_DETAILS);
    // Get the NTLM logon details
    String userName = type3Msg.getUserName();
    String workstation = type3Msg.getWorkstation();
    String domain = type3Msg.getDomain();
    // ALF-10997 fix, normalize the userName
    // the system runAs is acceptable because we are resolving a username i.e. it's a system-wide operation that does not need permission checks
    final String userName_f = userName;
    String normalized = transactionService.getRetryingTransactionHelper().doInTransaction(new RetryingTransactionHelper.RetryingTransactionCallback<String>() {

        public String execute() throws Throwable {
            return AuthenticationUtil.runAs(new AuthenticationUtil.RunAsWork<String>() {

                public String doWork() throws Exception {
                    String normalized = personService.getUserIdentifier(userName_f);
                    return normalized;
                }
            }, AuthenticationUtil.SYSTEM_USER_NAME);
        }
    }, true);
    if (normalized != null) {
        userName = normalized;
    }
    boolean authenticated = false;
    // Check if we are using cached details for the authentication
    if (user != null && ntlmDetails != null && ntlmDetails.hasNTLMHashedPassword()) {
        // Check if the received NTLM hashed password matches the cached password
        byte[] ntlmPwd = type3Msg.getNTLMHash();
        byte[] cachedPwd = ntlmDetails.getNTLMHashedPassword();
        if (ntlmPwd != null) {
            authenticated = Arrays.equals(cachedPwd, ntlmPwd);
        }
        if (logger.isDebugEnabled())
            logger.debug("Using cached NTLM hash, authenticated = " + authenticated);
        onValidate(context, req, res, new NTLMCredentials(userName, ntlmPwd));
        // Allow the user to access the requested page
        return true;
    } else {
        WebCredentials credentials;
        // Check if we are using local MD4 password hashes or passthru authentication
        if (nltmAuthenticator.getNTLMMode() == NTLMMode.MD4_PROVIDER) {
            // Check if guest logons are allowed and this is a guest logon
            if (m_allowGuest && userName.equalsIgnoreCase(authenticationComponent.getGuestUserName())) {
                credentials = new GuestCredentials();
                // Indicate that the user has been authenticated
                authenticated = true;
                if (getLogger().isDebugEnabled())
                    getLogger().debug("Guest logon");
            } else {
                // Get the stored MD4 hashed password for the user, or null if the user does not exist
                String md4hash = getMD4Hash(userName);
                if (md4hash != null) {
                    authenticated = validateLocalHashedPassword(type3Msg, ntlmDetails, authenticated, md4hash);
                    credentials = new NTLMCredentials(ntlmDetails.getUserName(), ntlmDetails.getNTLMHashedPassword());
                } else {
                    // Check if unknown users should be logged on as guest
                    if (m_mapUnknownUserToGuest) {
                        // Reset the user name to be the guest user
                        userName = authenticationComponent.getGuestUserName();
                        authenticated = true;
                        credentials = new GuestCredentials();
                        if (logger.isDebugEnabled())
                            logger.debug("User " + userName + " logged on as guest, no Alfresco account");
                    } else {
                        if (logger.isDebugEnabled())
                            logger.debug("User " + userName + " does not have Alfresco account");
                        // Bypass NTLM authentication and display the logon screen,
                        // as user account does not exist in Alfresco
                        credentials = new UnknownCredentials();
                        authenticated = false;
                    }
                }
            }
        } else {
            credentials = new NTLMCredentials(type3Msg.getUserName(), type3Msg.getNTLMHash());
            // Determine if the client sent us NTLMv1 or NTLMv2
            if (type3Msg.hasFlag(NTLM.Flag128Bit) && type3Msg.hasFlag(NTLM.FlagNTLM2Key) || (type3Msg.getNTLMHash() != null && type3Msg.getNTLMHash().length > 24)) {
                // Cannot accept NTLMv2 if we are using passthru auth
                if (logger.isErrorEnabled())
                    logger.error("Client " + workstation + " using NTLMv2 logon, not valid with passthru authentication");
            } else {
                if (ntlmDetails == null) {
                    if (logger.isWarnEnabled())
                        logger.warn("Authentication failed: NTLM details can not be retrieved from session. Client must support cookies.");
                    restartLoginChallenge(context, req, res);
                    return false;
                }
                // Passthru mode, send the hashed password details to the passthru authentication server
                NTLMPassthruToken authToken = (NTLMPassthruToken) ntlmDetails.getAuthenticationToken();
                authToken.setUserAndPassword(type3Msg.getUserName(), type3Msg.getNTLMHash(), PasswordEncryptor.NTLM1);
                try {
                    // Run the second stage of the passthru authentication
                    nltmAuthenticator.authenticate(authToken);
                    authenticated = true;
                    // Check if the user has been logged on as guest
                    if (authToken.isGuestLogon()) {
                        userName = authenticationComponent.getGuestUserName();
                    }
                    // Set the authentication context
                    authenticationComponent.setCurrentUser(userName);
                } catch (BadCredentialsException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication failed, " + ex.getMessage());
                } catch (AuthenticationException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Authentication failed, " + ex.getMessage());
                } finally {
                    // Clear the authentication token from the NTLM details
                    ntlmDetails.setAuthenticationToken(null);
                }
            }
        }
        // Check if the user has been authenticated, if so then setup the user environment
        if (authenticated == true) {
            boolean userInit = false;
            if (user == null) {
                try {
                    user = createUserEnvironment(session, userName);
                    userInit = true;
                } catch (AuthenticationException ex) {
                    if (logger.isDebugEnabled())
                        logger.debug("Failed to validate user " + userName, ex);
                    onValidateFailed(context, req, res, session, credentials);
                    return false;
                }
            }
            onValidate(context, req, res, credentials);
            // Update the NTLM logon details in the session
            String srvName = getServerName();
            if (ntlmDetails == null) {
                // No cached NTLM details
                ntlmDetails = new NTLMLogonDetails(userName, workstation, domain, false, srvName);
                ntlmDetails.setNTLMHashedPassword(type3Msg.getNTLMHash());
                session.setAttribute(NTLM_AUTH_DETAILS, ntlmDetails);
                if (logger.isDebugEnabled())
                    logger.debug("No cached NTLM details, created");
            } else {
                // Update the cached NTLM details
                ntlmDetails.setDetails(userName, workstation, domain, false, srvName);
                ntlmDetails.setNTLMHashedPassword(type3Msg.getNTLMHash());
                if (logger.isDebugEnabled())
                    logger.debug("Updated cached NTLM details");
            }
            if (logger.isDebugEnabled())
                logger.debug("User logged on via NTLM, " + ntlmDetails);
            if (onLoginComplete(context, req, res, userInit)) {
                // Allow the user to access the requested page
                return true;
            }
        } else {
            restartLoginChallenge(context, req, res);
        }
    }
    return false;
}
Also used : NTLMCredentials(org.alfresco.repo.web.auth.NTLMCredentials) Log(org.apache.commons.logging.Log) NTLMLogonDetails(org.alfresco.jlan.server.auth.ntlm.NTLMLogonDetails) RetryingTransactionHelper(org.alfresco.repo.transaction.RetryingTransactionHelper) UnknownCredentials(org.alfresco.repo.web.auth.UnknownCredentials) AuthenticationException(org.alfresco.repo.security.authentication.AuthenticationException) HttpSession(javax.servlet.http.HttpSession) BadCredentialsException(net.sf.acegisecurity.BadCredentialsException) SessionUser(org.alfresco.repo.SessionUser) NTLMPassthruToken(org.alfresco.repo.security.authentication.ntlm.NTLMPassthruToken) WebCredentials(org.alfresco.repo.web.auth.WebCredentials) GuestCredentials(org.alfresco.repo.web.auth.GuestCredentials)

Example 17 with Log

use of org.apache.commons.logging.Log in project alfresco-remote-api by Alfresco.

the class HttpRangeProcessor method processMultiRange.

/**
 * Process multiple ranges.
 *
 * @param res        HttpServletResponse
 * @param range      Range header value
 * @param ref        NodeRef to the content for streaming
 * @param property   Content Property for the content
 * @param mimetype   Mimetype of the content
 * @param userAgent  User Agent of the caller
 *
 * @return true if processed range, false otherwise
 */
private boolean processMultiRange(Object res, String range, NodeRef ref, QName property, String mimetype, String userAgent) throws IOException {
    final Log logger = getLogger();
    // Handle either HttpServletResponse or WebScriptResponse
    HttpServletResponse httpServletResponse = null;
    WebScriptResponse webScriptResponse = null;
    if (res instanceof HttpServletResponse) {
        httpServletResponse = (HttpServletResponse) res;
    } else if (res instanceof WebScriptResponse) {
        webScriptResponse = (WebScriptResponse) res;
    }
    if (httpServletResponse == null && webScriptResponse == null) {
        // Unknown response object type
        return false;
    }
    // return the sets of bytes as requested in the content-range header
    // the response will be formatted as multipart/byteranges media type message
    /* Examples of byte-ranges-specifier values (assuming an entity-body of length 10000):

       - The first 500 bytes (byte offsets 0-499, inclusive):  bytes=0-499
       - The second 500 bytes (byte offsets 500-999, inclusive):
         bytes=500-999
       - The final 500 bytes (byte offsets 9500-9999, inclusive):
         bytes=-500
       - Or bytes=9500-
       - The first and last bytes only (bytes 0 and 9999):  bytes=0-0,-1
       - Several legal but not canonical specifications of byte offsets 500-999, inclusive:
          bytes=500-600,601-999
          bytes=500-700,601-999 */
    boolean processedRange = false;
    // get the content reader
    ContentReader reader = contentService.getReader(ref, property);
    final List<Range> ranges = new ArrayList<Range>(8);
    long entityLength = reader.getSize();
    for (StringTokenizer t = new StringTokenizer(range, ", "); t.hasMoreTokens(); ) /**/
    {
        try {
            ranges.add(Range.constructRange(t.nextToken(), mimetype, entityLength));
        } catch (IllegalArgumentException err) {
            if (getLogger().isDebugEnabled())
                getLogger().debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
            if (httpServletResponse != null) {
                httpServletResponse.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                httpServletResponse.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
                httpServletResponse.getOutputStream().close();
            } else if (webScriptResponse != null) {
                webScriptResponse.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
                webScriptResponse.setHeader(HEADER_CONTENT_RANGE, "\"*\"");
                webScriptResponse.getOutputStream().close();
            }
            return true;
        }
    }
    if (ranges.size() != 0) {
        // merge byte ranges if possible - IE handles this well, FireFox not so much
        if (userAgent == null || userAgent.indexOf("MSIE ") != -1) {
            Collections.sort(ranges);
            for (int i = 0; i < ranges.size() - 1; i++) {
                Range first = ranges.get(i);
                Range second = ranges.get(i + 1);
                if (first.end + 1 >= second.start) {
                    if (logger.isDebugEnabled())
                        logger.debug("Merging byte range: " + first + " with " + second);
                    if (first.end < second.end) {
                        // merge second range into first
                        first.end = second.end;
                    }
                    // else we simply discard the second range - it is contained within the first
                    // delete second range
                    ranges.remove(i + 1);
                    // reset loop index
                    i--;
                }
            }
        }
        // calculate response content length
        long length = MULTIPART_BYTERANGES_BOUNDRY_END.length() + 2;
        for (Range r : ranges) {
            length += r.getLength();
        }
        // output headers as we have at least one range to process
        OutputStream os = null;
        if (httpServletResponse != null) {
            httpServletResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            httpServletResponse.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER);
            httpServletResponse.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length));
            os = httpServletResponse.getOutputStream();
        } else if (webScriptResponse != null) {
            webScriptResponse.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
            webScriptResponse.setHeader(HEADER_CONTENT_TYPE, MULTIPART_BYTERANGES_HEADER);
            webScriptResponse.setHeader(HEADER_CONTENT_LENGTH, Long.toString(length));
            os = webScriptResponse.getOutputStream();
        }
        InputStream is = null;
        try {
            for (Range r : ranges) {
                if (logger.isDebugEnabled())
                    logger.debug("Processing: " + r.getContentRange());
                try {
                    // output the header bytes for the range
                    if (os instanceof ServletOutputStream)
                        r.outputHeader((ServletOutputStream) os);
                    // output the binary data for the range
                    // need a new reader for each new InputStream
                    is = contentService.getReader(ref, property).getContentInputStream();
                    streamRangeBytes(r, is, os, 0L);
                    is.close();
                    is = null;
                    // section marker and flush stream
                    if (os instanceof ServletOutputStream)
                        ((ServletOutputStream) os).println();
                    os.flush();
                } catch (IOException err) {
                    if (getLogger().isDebugEnabled())
                        getLogger().debug("Unable to process multiple range due to IO Exception: " + err.getMessage());
                    throw err;
                }
            }
        } finally {
            if (is != null) {
                is.close();
            }
        }
        // end marker
        if (os instanceof ServletOutputStream)
            ((ServletOutputStream) os).println(MULTIPART_BYTERANGES_BOUNDRY_END);
        os.close();
        processedRange = true;
    }
    return processedRange;
}
Also used : Log(org.apache.commons.logging.Log) ServletOutputStream(javax.servlet.ServletOutputStream) InputStream(java.io.InputStream) ContentReader(org.alfresco.service.cmr.repository.ContentReader) OutputStream(java.io.OutputStream) ServletOutputStream(javax.servlet.ServletOutputStream) ArrayList(java.util.ArrayList) HttpServletResponse(javax.servlet.http.HttpServletResponse) IOException(java.io.IOException) StringTokenizer(java.util.StringTokenizer) WebScriptResponse(org.springframework.extensions.webscripts.WebScriptResponse)

Example 18 with Log

use of org.apache.commons.logging.Log in project pentaho-platform by pentaho.

the class RepositoryFileImportFileHandlerTest method testGetLogger.

@Test
public void testGetLogger() {
    setup(MIMENAME, MIME_EXTENSION, "", "", false);
    Log logger = fileHandler.getLogger();
    assertNotNull(logger);
}
Also used : Log(org.apache.commons.logging.Log) Test(org.junit.Test)

Example 19 with Log

use of org.apache.commons.logging.Log in project pentaho-platform by pentaho.

the class PentahoMetadataDomainRepositoryTest method testCreateOrUpdateAnnotationsXml.

@Test
public void testCreateOrUpdateAnnotationsXml() throws Exception {
    String metadataDirId = "00000000";
    String annotationsXml = "<annotations/>";
    RepositoryFile metaDataDir = mock(RepositoryFile.class);
    IUnifiedRepository repository = mock(IUnifiedRepository.class);
    Log logger = mock(Log.class);
    doReturn(logger).when(domainRepositorySpy).getLogger();
    doReturn(repository).when(domainRepositorySpy).getRepository();
    doReturn(metadataDirId).when(metaDataDir).getId();
    doReturn(metaDataDir).when(domainRepositorySpy).getMetadataDir();
    // Domain Not Found
    domainRepositorySpy.createOrUpdateAnnotationsXml(null, null, annotationsXml);
    verify(domainRepositorySpy, times(0)).getRepository();
    RepositoryFile domainFile = mock(RepositoryFile.class);
    // Create
    domainRepositorySpy.createOrUpdateAnnotationsXml(domainFile, null, annotationsXml);
    verify(repository, times(1)).createFile(any(String.class), any(RepositoryFile.class), any(IRepositoryFileData.class), any(String.class));
    // Update
    RepositoryFile annotationsFile = mock(RepositoryFile.class);
    domainRepositorySpy.createOrUpdateAnnotationsXml(domainFile, annotationsFile, annotationsXml);
    verify(repository, times(1)).updateFile(any(RepositoryFile.class), any(IRepositoryFileData.class), any(String.class));
    // Error
    doThrow(new RuntimeException()).when(domainRepositorySpy).getRepository();
    domainRepositorySpy.createOrUpdateAnnotationsXml(domainFile, annotationsFile, annotationsXml);
    verify(logger, times(1)).warn(any(), any(Throwable.class));
}
Also used : IRepositoryFileData(org.pentaho.platform.api.repository2.unified.IRepositoryFileData) Log(org.apache.commons.logging.Log) RepositoryFile(org.pentaho.platform.api.repository2.unified.RepositoryFile) Matchers.anyString(org.mockito.Matchers.anyString) IUnifiedRepository(org.pentaho.platform.api.repository2.unified.IUnifiedRepository) Test(org.junit.Test)

Example 20 with Log

use of org.apache.commons.logging.Log in project pentaho-platform by pentaho.

the class PentahoMetadataDomainRepositoryTest method testGetAnnotationsXmlFile.

@Test
public void testGetAnnotationsXmlFile() throws Exception {
    String domainFileId = "00000000";
    assertNull(domainRepositorySpy.getAnnotationsXmlFile(null));
    Log logger = mock(Log.class);
    doReturn(logger).when(domainRepositorySpy).getLogger();
    IUnifiedRepository repository = mock(IUnifiedRepository.class);
    doReturn(repository).when(domainRepositorySpy).getRepository();
    RepositoryFile domainFile = mock(RepositoryFile.class);
    doReturn(domainFileId).when(domainFile).getId();
    // Not Found
    doReturn(domainFile).when(repository).getFileById("someOtherId");
    assertNull(domainRepositorySpy.getAnnotationsXmlFile(domainFile));
    // Found
    String annotationsFilePath = File.separator + "etc" + File.separator + "metadata/" + domainFileId + IModelAnnotationsAwareMetadataDomainRepositoryImporter.ANNOTATIONS_FILE_ID_POSTFIX;
    doReturn(domainFile).when(repository).getFile(annotationsFilePath);
    assertNotNull(domainRepositorySpy.getAnnotationsXmlFile(domainFile));
    // Error
    doThrow(new RuntimeException()).when(domainRepositorySpy).getRepository();
    assertNull(domainRepositorySpy.getAnnotationsXmlFile(domainFile));
    verify(logger, times(1)).warn("Unable to find annotations xml file for: " + domainFile.getId());
}
Also used : Log(org.apache.commons.logging.Log) RepositoryFile(org.pentaho.platform.api.repository2.unified.RepositoryFile) Matchers.anyString(org.mockito.Matchers.anyString) IUnifiedRepository(org.pentaho.platform.api.repository2.unified.IUnifiedRepository) Test(org.junit.Test)

Aggregations

Log (org.apache.commons.logging.Log)188 Test (org.junit.Test)51 Test (org.junit.jupiter.api.Test)40 DirectFieldAccessor (org.springframework.beans.DirectFieldAccessor)35 ArgumentMatchers.anyString (org.mockito.ArgumentMatchers.anyString)19 BeanFactory (org.springframework.beans.factory.BeanFactory)17 CountDownLatch (java.util.concurrent.CountDownLatch)15 LogConfigurationException (org.apache.commons.logging.LogConfigurationException)15 ArrayList (java.util.ArrayList)12 File (java.io.File)11 QueueChannel (org.springframework.integration.channel.QueueChannel)11 MethodInvocation (org.aopalliance.intercept.MethodInvocation)10 IOException (java.io.IOException)9 AtomicReference (java.util.concurrent.atomic.AtomicReference)9 Log4JLogger (org.apache.commons.logging.impl.Log4JLogger)9 Message (org.springframework.messaging.Message)8 List (java.util.List)7 ApplicationEventPublisher (org.springframework.context.ApplicationEventPublisher)7 InputStream (java.io.InputStream)6 LogFactory (org.apache.commons.logging.LogFactory)6