Masking nested objects in Spring boot using logstash-logback-encoder

252 Views Asked by At

I want to mask the password field of the log- {"timestamp":"2021-10-26T22:41:29.471+02:00","level":"INFO", "body":[{"id":1,"password": "ABC"},{"id":2,"password":"DEF"},{"id":3,"password":"my-super-secure-password"}]"}

I was reading the solution provided in the link- https://github.com/logfellow/logstash-logback-encoder/discussions/685

But I am unable to derive the solution mentioned in the blog. Can someone help me?

I tried it using the ValueMasker in logstash library


import com.fasterxml.jackson.core.JsonStreamContext;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import net.logstash.logback.mask.ValueMasker;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;


@Slf4j
@Component
public class RegexFindValueMasker implements ValueMasker {

  private final List<Pattern> patterns;

  public RegexFindValueMasker() {
    patterns = new ArrayList<>();
    patterns.add(Pattern.compile("password[:=][^,]*"));
  }

  @Override
  public Object mask(JsonStreamContext context, Object value) {
    if (context.getCurrentName() == MESSAGE && value instanceof String) {
      String valueStr = (String) value;

      log.info("INSIDE MASK FUNCTION");

      List<String> matchedLabels = new ArrayList<>();
      for (Pattern pattern : patterns) {
        Matcher matcher = pattern.matcher(valueStr);
        while (matcher.find()) {
          log.info("ONE MATCH FOUND");
          matchedLabels.add(matcher.group(1));
        }
      }

      String newValue = valueStr;
      for (String matchedLabel : matchedLabels) {
        log.info("REPLACING VALUES");
        newValue = newValue.replace(matchedLabel, MASK);
      }
      return newValue;
    } else {
      return null;
    }
  }

  private static final String MESSAGE = "message";
  private static final String MASK = "*****";
}

But it is not working

0

There are 0 best solutions below