scrubSensitiveData function

String scrubSensitiveData(
  1. String message
)

Censores sensitive data in log messages.

Implementation

String scrubSensitiveData(String message) {
  var scrubbed = message;

  final patterns = [
    // Key-Value Pairs
    for (final key in sensitiveKeys) RegExp(r'(\b' + key + r'\b\s*=\s*)([^&\s,]*)', caseSensitive: false, multiLine: true),

    // Json values
    for (final key in sensitiveKeys) RegExp(r'(\b' + key + r'\b\s*:\s*)([^&\s,}]*)', caseSensitive: false, multiLine: true),

    // Bearer Tokens
    RegExp(r'(Bearer\s+)([^\s]*)', caseSensitive: false),
    // Basic Auth
    RegExp(r'(Basic\s+)([^\s]*)', caseSensitive: false),
    // JWT Tokens
    RegExp(r'(JWT\s+)([^\s]*)', caseSensitive: false),
  ];

  for (final pattern in patterns) {
    scrubbed = scrubbed.replaceAllMapped(pattern, (match) {
      final key = match.group(1);
      final value = match.group(2);

      final length = value?.length ?? 1;

      return '$key${'*' * length}';
    });
  }

  return scrubbed;
}