serilog-contrib / Serilog.Enrichers.Sensitive

A Serilog LogEvent enricher that masks sensitive data
MIT License
111 stars 23 forks source link

Partial Email masking #19

Closed SViradiya-MarutiTech closed 1 year ago

SViradiya-MarutiTech commented 1 year ago

is there any way I can mask tony.alex@gmail.com to to**@g**.com

sandermvanvliet commented 1 year ago

Currently that is not possible because, unfortunately, the PreprocessMask method doesn’t receive the matched email address and the sink doesn’t support specifying a regex as the mask value.

You could create a new masking operator and combine parts from the RegexMaskingOperator and the EmailAddressMaskingOperator to make that work.

But do note that the email regex isn’t trivial

sandermvanvliet commented 1 year ago

A quick and dirty approach:

public new MaskingResult Mask(string input, string mask)
{
    var preprocessedInput = PreprocessInput(input);

    if (!ShouldMaskInput(preprocessedInput))
    {
        return MaskingResult.NoMatch;
    }

    var maskedResult = _thisRegex.Replace(preprocessedInput, match =>
    {
        if (ShouldMaskMatch(match))
        {
            var replacement = PreprocessMask(mask);

            var parts = match.Value.Split('@');
            if (parts.Length == 2)
            {
                if (parts[0].Length > 2)
                {
                    replacement = parts[0][..2] + "**";
                }
                else
                {
                    replacement = parts[0][0] + "**";
                }

                var tldDotPos = parts[1].LastIndexOf('.');
                var domain = parts[1][..tldDotPos];
                replacement += "@" + parts[1].Replace(domain, domain[0] + "**");
            }

            return match.Result(replacement);
        }

        return match.Value;
    });

    var result = new MaskingResult
    {
        Result = maskedResult,
        Match = maskedResult != input
    };

    return result;
}
sandermvanvliet commented 1 year ago

The upcoming release will allow you to access the match value through the PreprocessMask(string mask, Match match) overload. You can override this in a custom masking operator class to perform more dynamic masking like what you're looking for.

See here for the relevant documentation.