Skip to content

Instantly share code, notes, and snippets.

@mayuki
Created October 17, 2019 09:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mayuki/0d84d3d0b2bf8f089f69b042f4b650b8 to your computer and use it in GitHub Desktop.
Save mayuki/0d84d3d0b2bf8f089f69b042f4b650b8 to your computer and use it in GitHub Desktop.
Configuration をログに
string BuildConfigurationLog(IConfiguration configuration)
{
var stringBuilder = new StringBuilder();
foreach (var child in configuration.GetChildren())
{
if (child.Value == null)
{
TraverseConfiguration(child, stringBuilder);
}
else
{
// Value != null は文字列が設定されているもの
// ルートで文字列なのはだいたい環境変数なのでスキップする
}
}
return stringBuilder.ToString();
void TraverseConfiguration(IConfigurationSection section, StringBuilder sb)
{
if (section.Value is null)
{
var children = section.GetChildren();
if (children != null)
{
foreach (var child in children)
{
TraverseConfiguration(child, sb);
}
return;
}
}
sb.AppendLine($"{section.Path}: {MaskSecrets(section)}");
}
string MaskSecrets(IConfigurationSection section)
{
if (section.Key.EndsWith("Key", StringComparison.OrdinalIgnoreCase) ||
section.Key.Contains("Password", StringComparison.OrdinalIgnoreCase) ||
section.Key.Contains("Secret", StringComparison.OrdinalIgnoreCase) ||
section.Key.Contains("Token", StringComparison.OrdinalIgnoreCase))
{
return $"<Secret Hash={HashString(section.Value)}>";
}
else
{
return Regex.Replace(section.Value, "(password|authtoken)=([^;]+)", (m) => $"{m.Groups[1].Value}=<Secret Hash={HashString(m.Groups[2].Value)}>", RegexOptions.IgnoreCase);
}
}
string HashString(string value)
{
using (var hmac = new HMACSHA256(Encoding.UTF8.GetBytes(typeof(Program).Assembly.FullName)))
{
return String.Concat(hmac.ComputeHash(Encoding.UTF8.GetBytes(value)).Select(x => x.ToString("x2"))).Substring(0, 6);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment