redactrus

package module
v0.0.0-...-a14f63a Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 5, 2026 License: MIT Imports: 9 Imported by: 0

README

Redactrus

░       ░░░        ░░       ░░░░      ░░░░      ░░░        ░░       ░░░  ░░░░  ░░░      ░░
▒  ▒▒▒▒  ▒▒  ▒▒▒▒▒▒▒▒  ▒▒▒▒  ▒▒  ▒▒▒▒  ▒▒  ▒▒▒▒  ▒▒▒▒▒  ▒▒▒▒▒  ▒▒▒▒  ▒▒  ▒▒▒▒  ▒▒  ▒▒▒▒▒▒▒
▓       ▓▓▓      ▓▓▓▓  ▓▓▓▓  ▓▓  ▓▓▓▓  ▓▓  ▓▓▓▓▓▓▓▓▓▓▓  ▓▓▓▓▓       ▓▓▓  ▓▓▓▓  ▓▓▓      ▓▓
█  ███  ███  ████████  ████  ██        ██  ████  █████  █████  ███  ███  ████  ████████  █
█  ████  ██        ██       ███  ████  ███      ██████  █████  ████  ███      ████      ██
                                                                                          

Go Reference CI Status Go Version License

Redactrus is a high-performance, production-grade security logging library for Go. It intercepts, sanitizes, and redacts sensitive data (such as passwords, API keys, JWTs, credit cards, emails, and SSNs) before it hits your logging sink.

It provides seamless adapters for logrus, standard library slog, zerolog, and any raw io.Writer streams.


Features

  • 8+ Built-in Redactors: Out-of-the-box support for Password, APIKey, Email, JWT, BearerToken, AWSAccessKey, CreditCard, and SSN.
  • Field-level & String-level Redaction: Scrub structured JSON fields by exact key name or key pattern, and perform deep regex redaction on message text.
  • HMAC Hash-based Redaction: Replace sensitive data with deterministic [HASHED:<hex>] signatures to correlate events across systems safely.
  • OnRedaction Callbacks: Monitor and audit potential leaks in real-time.
  • Multi-framework Support: Works out of the box with sirupsen/logrus, log/slog, rs/zerolog, or any custom writer via io.Writer.
  • Zero Allocations & Thread-safe: Regexes are pre-compiled and access is protected by standard synchronization.

Installation

go get github.com/ibreakthecloud/redactrus

Requires Go 1.23 or newer.


Usage

1. Logrus Wrapper (Field & Message Redaction)
import (
	"github.com/ibreakthecloud/redactrus"
	"github.com/sirupsen/logrus"
)

func main() {
	logger := logrus.New()
	
	// Create formatter wrapping standard logrus formatter
	formatter := redactrus.NewDefaultRedactingFormatter(&logrus.JSONFormatter{}).
		RedactFields("password", "api_key") // Redact structured field keys
		
	logger.SetFormatter(formatter)

	// Will redact message string and structured entry fields
	logger.WithField("password", "123").Info("User logging in with password=123")
}
2. Standard slog Handler (Go 1.21+)
import (
	"log/slog"
	"os"
	"github.com/ibreakthecloud/redactrus"
)

func main() {
	formatter := redactrus.NewDefaultRedactingFormatter(&logrus.JSONFormatter{}).
		RedactFields("secret_token")

	// Wrap any slog.Handler (e.g. JSONHandler)
	handler := redactrus.NewRedactingHandler(slog.NewJSONHandler(os.Stdout, nil), formatter)
	logger := slog.New(handler)

	// Replaces value of secret_token with "[REDACTED]"
	logger.Info("sensitive operation", slog.String("secret_token", "supersecret"))
}
3. Zerolog & Byte-stream Writer Adapter
import (
	"os"
	"github.com/ibreakthecloud/redactrus"
	"github.com/rs/zerolog"
)

func main() {
	formatter := redactrus.NewDefaultRedactingFormatter(&logrus.JSONFormatter{})
	
	// Wrap stdout to intercept and redact raw streams
	writer := redactrus.NewZerologWriter(os.Stdout, formatter)
	logger := zerolog.New(writer).With().Timestamp().Logger()

	logger.Info().Msg("Accessing resource with api_key=sk-abc123XYZ")
}

Advanced Features

Deterministic Hash-based Redaction

Instead of placing generic [REDACTED] markers in logs, you can set a global HMAC key. Secrets will be replaced with their HMAC-SHA256 signature, preserving quotes:

// Set key for deterministic hashing
redactrus.SetGlobalHashKey([]byte("my-internal-secure-key-123"))

// A log containing "password=mysecret" becomes:
// "password=[HASHED:2c26b46b68ffc68ff99b453c1d30413413422d706483bfa0f98a5e886266e7ae]"
OnRedaction Auditing Callback

Get notified immediately when sensitive data is intercepted:

redactrus.SetGlobalRedactionCallback(func(redactorName, value string) {
	metrics.IncrementCounter("logs.redacted", "redactor", redactorName)
	if isHighlyCritical(value) {
		alerting.Notify("Security leak detected in logs!")
	}
})

Contributing

Contributions are welcome! Please read CONTRIBUTING.md and SECURITY.md before opening pull requests or reporting vulnerabilities.


License

This project is licensed under the MIT License - see the LICENSE file for details.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func APIKey

func APIKey(msg, r string) string

APIKey redacts api_key, apikey, and api-key fields (case-insensitive) from a log message.

func AWSAccessKey

func AWSAccessKey(msg, r string) string

AWSAccessKey redacts AWS Access Key ID and Secret Access Key from a log message.

func BearerToken

func BearerToken(msg, r string) string

BearerToken redacts Authorization Bearer tokens from a log message.

func CreditCard

func CreditCard(msg, r string) string

CreditCard redacts credit card numbers from a log message.

func Email

func Email(msg, r string) string

Email redacts email addresses from a log message.

func JWT

func JWT(msg, r string) string

JWT redacts JSON Web Tokens from a log message.

func NewZerologWriter

func NewZerologWriter(w io.Writer, formatter *RedactingFormatter) io.Writer

NewZerologWriter returns an io.Writer that wraps the provided io.Writer with a RedactingWriter, enabling integration with Zerolog's writer-based output.

func Password

func Password(msg, r string) string

Password redacts password, passwd, and pwd fields (case-insensitive) from a log message.

func SSN

func SSN(msg, r string) string

SSN redacts Social Security Numbers from a log message.

func SetGlobalHashKey

func SetGlobalHashKey(key []byte)

SetGlobalHashKey configures the global hash key used for dynamic HMAC-SHA256 redaction.

func SetGlobalRedactionCallback

func SetGlobalRedactionCallback(cb func(redactorName, value string))

SetGlobalRedactionCallback configures the global callback function invoked when a match is redacted.

Types

type RedactingFormatter

type RedactingFormatter struct {
	InnerFormatter logrus.Formatter
	RedactWith     string
	// contains filtered or unexported fields
}

RedactingFormatter struct that embeds logrus.Formatter and includes redaction functions. InnerFormatter and RedactWith are exported; redactors is unexported and protected by mu.

func NewDefaultRedactingFormatter

func NewDefaultRedactingFormatter(innerFormatter logrus.Formatter) *RedactingFormatter

NewDefaultRedactingFormatter creates a new RedactingFormatter with default redactors.

func NewRedactingFormatter

func NewRedactingFormatter(innerFormatter logrus.Formatter) *RedactingFormatter

NewRedactingFormatter creates a new RedactingFormatter with no redactors. RedactWith defaults to "[REDACTED]".

func (*RedactingFormatter) AddRedactor

func (f *RedactingFormatter) AddRedactor(redactor RedactionFunc) *RedactingFormatter

AddRedactor adds a new redaction function to the RedactingFormatter.

func (*RedactingFormatter) AddRedactors

func (f *RedactingFormatter) AddRedactors(redactors ...RedactionFunc) *RedactingFormatter

AddRedactors adds multiple redaction functions to the RedactingFormatter.

func (*RedactingFormatter) Format

func (f *RedactingFormatter) Format(entry *logrus.Entry) ([]byte, error)

Format formats the log entry, applying all redaction functions to the output.

func (*RedactingFormatter) RedactFieldPatterns

func (f *RedactingFormatter) RedactFieldPatterns() []*regexp.Regexp

RedactFieldPatterns returns a copy of the regex patterns configured for key-pattern field redaction.

func (*RedactingFormatter) RedactFields

func (f *RedactingFormatter) RedactFields(keys ...string) *RedactingFormatter

RedactFields adds one or more specific field keys to be redacted from logrus entry fields.

func (*RedactingFormatter) RedactFieldsByKeyPattern

func (f *RedactingFormatter) RedactFieldsByKeyPattern(patterns ...*regexp.Regexp) *RedactingFormatter

RedactFieldsByKeyPattern adds one or more regex patterns to match against entry field keys.

func (*RedactingFormatter) RedactFieldsList

func (f *RedactingFormatter) RedactFieldsList() []string

RedactFieldsList returns a list of exact keys configured for field redaction.

func (*RedactingFormatter) Redactors

func (f *RedactingFormatter) Redactors() []RedactionFunc

Redactors returns a copy of the current redactors slice for inspection or testing.

func (*RedactingFormatter) SetRedactWith

func (f *RedactingFormatter) SetRedactWith(r string) *RedactingFormatter

SetRedactWith sets the string to redact sensitive information with.

type RedactingHandler

type RedactingHandler struct {
	// contains filtered or unexported fields
}

RedactingHandler wraps an slog.Handler and redacts matching attributes.

func NewRedactingHandler

func NewRedactingHandler(h slog.Handler, formatter *RedactingFormatter) *RedactingHandler

NewRedactingHandler creates a new RedactingHandler.

func (*RedactingHandler) Enabled

func (h *RedactingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled delegates the Enabled check to the inner handler.

func (*RedactingHandler) Handle

func (h *RedactingHandler) Handle(ctx context.Context, record slog.Record) error

Handle copies the record, redacts its attributes, and delegates to the inner handler.

func (*RedactingHandler) WithAttrs

func (h *RedactingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new RedactingHandler with the given attributes redacted and added.

func (*RedactingHandler) WithGroup

func (h *RedactingHandler) WithGroup(name string) slog.Handler

WithGroup returns a new RedactingHandler wrapping the inner handler with the group.

type RedactingWriter

type RedactingWriter struct {
	// contains filtered or unexported fields
}

RedactingWriter wraps an io.Writer and applies string-level redactions to all written data.

func NewRedactingWriter

func NewRedactingWriter(w io.Writer, formatter *RedactingFormatter) *RedactingWriter

NewRedactingWriter creates a new RedactingWriter with the given io.Writer and RedactingFormatter.

func (*RedactingWriter) Write

func (rw *RedactingWriter) Write(p []byte) (n int, err error)

Write converts p to a string, runs all string-level redactors from the formatter, writes the redacted string to the underlying writer, and returns len(p), nil on success.

type RedactionFunc

type RedactionFunc func(string, string) string

RedactionFunc type for functions that redact sensitive information

Directories

Path Synopsis
examples
basic command
custom-redactor command
only-email command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL