Search code examples
javaloggingjavax.ws.rsjavax

How to prevent sensitive data from being logged by SyncInvoker.post?


I'm sending a request with a following code:

final WebTarget target = client.target(url);
CustomResponse response = target.request(MediaType.APPLICATION_XML_TYPE)
                          .post(Entity.xml(password), CustomResponse.class);

Authentication is designed to accept username as a part of url while password is sent in request body.

The issue is that password is shown in logs which are generated by class ClientRequest#writeEntity() inside javax.ws.rs library.

So, my question is how force that library not to store password in logs without turning logging off?

Thank you.


Solution

  • Create a custom java.util.logging.Filter and install it on the java.util.logging.Logger that is generating the log record. You can either just omit that log entry by returning false or simply re-write the parameter or message of the log record so that it doesn't contain the password.

    import java.util.logging.Filter;
    import java.util.logging.LogRecord;
    
    
    public class PasswordFilter implements Filter {
    
        @Override
        public boolean isLoggable(LogRecord record) {
            if (isPasswordCallSite(record)) {
               //return false; // omit log entry.
               //Or hide password.
               Object[] params = record.getParameters();
               if (params != null && params.length != 0) {
                   params = params.clone();
                   String data = String.valueOf(params[0]);
    
                    //Write code to find and replace password.
                   params[0] = data;
                   record.setParameters(params);
               }
            }
            return true;
        }
    
        private boolean isPasswordCallSite(LogRecord r) {
            return "foo.bar.ClientRequest".equals(r.getSourceClassName())
                    && "writeEntity".equals(r.getSourceMethodName());
        }
    }