Skip to content

Commit

Permalink
add logs scrubber to config for removing secrets, includes test
Browse files Browse the repository at this point in the history
  • Loading branch information
whossname committed Feb 8, 2022
1 parent b75164e commit 4143751
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 5 deletions.
19 changes: 15 additions & 4 deletions lib/slack_logger_backend/format_helper.ex
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ defmodule SlackLoggerBackend.FormatHelper do
Simple formatter for Slack messages.
"""

import Poison, only: [encode: 1]

@doc """
Formats a log event for Slack.
"""
Expand All @@ -22,7 +20,12 @@ defmodule SlackLoggerBackend.FormatHelper do
]
|> Enum.reject(&is_nil/1)

message = messge_to_string(detail.message)
scrubber = Application.get_env(:slack_logger_backend, :scrubber)

message =
detail.message
|> messge_to_string()
|> scrub(scrubber)

{:ok, json} =
%{
Expand All @@ -34,7 +37,7 @@ defmodule SlackLoggerBackend.FormatHelper do
}
]
}
|> encode
|> Poison.encode()

json
end
Expand All @@ -49,6 +52,14 @@ defmodule SlackLoggerBackend.FormatHelper do
)
end

defp scrub(message, nil), do: message

defp scrub(message, {regex, substitution}),
do: String.replace(message, regex, substitution, global: true)

defp scrub(message, regex),
do: String.replace(message, regex, "--redacted--", global: true)

defp field(title, map, key), do: field(title, map[key])
defp field(_, nil), do: nil

Expand Down
26 changes: 26 additions & 0 deletions test/slack_logger_backend/format_helper_test.exs
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
defmodule SlackLoggerBackend.FormatHelperTest do
alias SlackLoggerBackend.FormatHelper

use ExUnit.Case

test "scrubber redacts secrets" do
scrubber = {~r/(password: \")(.+)(\")/, "\\1--redadacted--\\3"}
Application.put_env(:slack_logger_backend, :scrubber, scrubber)

message =
%{level: "error", message: "username: \"user\", password: \"password\""}
|> FormatHelper.format_event()
|> get_message()

assert message == "username: \"user\", password: \"--redadacted--\""
end

defp get_message(message) do
message
|> Poison.decode()
|> elem(1)
|> Map.get("attachments")
|> List.first()
|> Map.get("pretext")
end
end
2 changes: 1 addition & 1 deletion test/slack_logger_backend/pool_worker_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ ExUnit.start()

defmodule SlackLoggerBackend.PoolWorkerTest do
use ExUnit.Case
alias SlackLoggerBackend.{PoolWorker}
alias SlackLoggerBackend.PoolWorker

setup do
bypass = Bypass.open()
Expand Down

0 comments on commit 4143751

Please sign in to comment.