221 lines
6.4 KiB
Go
221 lines
6.4 KiB
Go
package telemetry
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"regexp"
|
|
|
|
"go.opentelemetry.io/contrib/bridges/otelslog"
|
|
"go.opentelemetry.io/otel/trace"
|
|
|
|
"mtusi-messenger/internal/platform/instanceid"
|
|
)
|
|
|
|
var (
|
|
allowKeys = map[string]struct{}{
|
|
"event": {}, "operation": {}, "route": {}, "method": {}, "status": {},
|
|
"status_class": {}, "duration": {}, "error_code": {}, "job_type": {},
|
|
"outcome": {}, "attempt": {}, "pipeline_version": {}, "queue": {},
|
|
"count": {}, "bytes": {}, "size": {}, "job_id": {},
|
|
"service.name": {}, "service.instance.id": {},
|
|
"deployment.environment.name": {}, "trace_id": {}, "span_id": {},
|
|
"request_id": {}, "error": {},
|
|
}
|
|
requestIDPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
|
jobIDPattern = regexp.MustCompile(`^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$`)
|
|
redactPatterns = []*regexp.Regexp{
|
|
regexp.MustCompile(`(?i)(X-Amz-(?:Signature|Credential|Security-Token)=)[^&\s"]+`),
|
|
regexp.MustCompile(`(?i)(password|passwd|secret|token|authorization)=([^&\s"]+)`),
|
|
regexp.MustCompile(`://[^/\s:@]+:[^@\s]+@`),
|
|
regexp.MustCompile(`(?i)\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b`),
|
|
regexp.MustCompile(`\b(?:attachments|staging|variants)/[^\s"']+`),
|
|
}
|
|
)
|
|
|
|
// WrapLogger returns a logger that writes sanitized JSON to stdout and, when
|
|
// configured, also emits OTLP log records. The sanitizer is the boundary that
|
|
// prevents raw paths, filenames, user ids and credentials from reaching any
|
|
// telemetry backend.
|
|
func WrapLogger(base *slog.Logger, serviceName string, minLevel slog.Level) *slog.Logger {
|
|
if base == nil {
|
|
base = slog.Default()
|
|
}
|
|
|
|
var otelHandler slog.Handler
|
|
if provider := GlobalLoggerProvider(); provider != nil {
|
|
otelHandler = otelslog.NewHandler("messenger", otelslog.WithLoggerProvider(provider))
|
|
}
|
|
|
|
return slog.New(&sanitizeHandler{
|
|
inner: &fanoutHandler{handlers: []slog.Handler{base.Handler(), otelHandler}},
|
|
service: serviceName,
|
|
instance: instanceid.FromEnvOrHostname(),
|
|
minLevel: minLevel,
|
|
})
|
|
}
|
|
|
|
type fanoutHandler struct {
|
|
handlers []slog.Handler
|
|
}
|
|
|
|
func (h *fanoutHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
|
for _, handler := range h.handlers {
|
|
if handler != nil && handler.Enabled(ctx, level) {
|
|
return true
|
|
}
|
|
}
|
|
return false
|
|
}
|
|
|
|
func (h *fanoutHandler) Handle(ctx context.Context, record slog.Record) error {
|
|
for _, handler := range h.handlers {
|
|
if handler == nil {
|
|
continue
|
|
}
|
|
if err := handler.Handle(ctx, record.Clone()); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func (h *fanoutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
next := &fanoutHandler{handlers: make([]slog.Handler, 0, len(h.handlers))}
|
|
for _, handler := range h.handlers {
|
|
if handler == nil {
|
|
next.handlers = append(next.handlers, nil)
|
|
continue
|
|
}
|
|
next.handlers = append(next.handlers, handler.WithAttrs(attrs))
|
|
}
|
|
return next
|
|
}
|
|
|
|
func (h *fanoutHandler) WithGroup(name string) slog.Handler {
|
|
next := &fanoutHandler{handlers: make([]slog.Handler, 0, len(h.handlers))}
|
|
for _, handler := range h.handlers {
|
|
if handler == nil {
|
|
next.handlers = append(next.handlers, nil)
|
|
continue
|
|
}
|
|
next.handlers = append(next.handlers, handler.WithGroup(name))
|
|
}
|
|
return next
|
|
}
|
|
|
|
type sanitizeHandler struct {
|
|
inner slog.Handler
|
|
service string
|
|
instance string
|
|
minLevel slog.Level
|
|
}
|
|
|
|
func (h *sanitizeHandler) Enabled(ctx context.Context, level slog.Level) bool {
|
|
return level >= h.minLevel && h.inner.Enabled(ctx, level)
|
|
}
|
|
|
|
func (h *sanitizeHandler) Handle(ctx context.Context, record slog.Record) error {
|
|
sanitized := slog.NewRecord(record.Time, record.Level, sanitizeText(record.Message), record.PC)
|
|
|
|
seenEvent := false
|
|
record.Attrs(func(attr slog.Attr) bool {
|
|
if attr.Key == "event" {
|
|
seenEvent = true
|
|
}
|
|
if clean, ok := sanitizeAttr(attr); ok {
|
|
sanitized.AddAttrs(clean)
|
|
}
|
|
return true
|
|
})
|
|
|
|
if !seenEvent {
|
|
event := sanitizeText(record.Message)
|
|
if event == "" {
|
|
event = "log"
|
|
}
|
|
sanitized.AddAttrs(slog.String("event", event))
|
|
}
|
|
if h.service != "" {
|
|
sanitized.AddAttrs(slog.String("service.name", h.service))
|
|
}
|
|
if h.instance != "" {
|
|
sanitized.AddAttrs(slog.String("service.instance.id", h.instance))
|
|
}
|
|
if spanContext := trace.SpanContextFromContext(ctx); spanContext.IsValid() {
|
|
sanitized.AddAttrs(
|
|
slog.String("trace_id", spanContext.TraceID().String()),
|
|
slog.String("span_id", spanContext.SpanID().String()),
|
|
)
|
|
}
|
|
|
|
return h.inner.Handle(ctx, sanitized)
|
|
}
|
|
|
|
func (h *sanitizeHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
|
|
clean := make([]slog.Attr, 0, len(attrs))
|
|
for _, attr := range attrs {
|
|
if value, ok := sanitizeAttr(attr); ok {
|
|
clean = append(clean, value)
|
|
}
|
|
}
|
|
return &sanitizeHandler{inner: h.inner.WithAttrs(clean), service: h.service, instance: h.instance, minLevel: h.minLevel}
|
|
}
|
|
|
|
func (h *sanitizeHandler) WithGroup(name string) slog.Handler {
|
|
return &sanitizeHandler{inner: h.inner.WithGroup(name), service: h.service, instance: h.instance, minLevel: h.minLevel}
|
|
}
|
|
|
|
func sanitizeAttr(attr slog.Attr) (slog.Attr, bool) {
|
|
if _, ok := allowKeys[attr.Key]; !ok {
|
|
return slog.Attr{}, false
|
|
}
|
|
|
|
value := attr.Value.Resolve()
|
|
switch attr.Key {
|
|
case "error":
|
|
return slog.String("error", Redact(value.String())), true
|
|
case "request_id":
|
|
id := value.String()
|
|
if !requestIDPattern.MatchString(id) {
|
|
id = "invalid"
|
|
}
|
|
return slog.String("request_id", id), true
|
|
case "job_id":
|
|
// job_id is an explicitly allowlisted synthetic/technical identifier.
|
|
// Unlike free-form error text, it is safe to keep for queue correlation.
|
|
id := value.String()
|
|
if !jobIDPattern.MatchString(id) {
|
|
id = "invalid"
|
|
}
|
|
return slog.String("job_id", id), true
|
|
}
|
|
|
|
if value.Kind() == slog.KindGroup {
|
|
return slog.Attr{}, false
|
|
}
|
|
if value.Kind() == slog.KindString {
|
|
return slog.String(attr.Key, sanitizeText(value.String())), true
|
|
}
|
|
return slog.Attr{Key: attr.Key, Value: value}, true
|
|
}
|
|
|
|
func sanitizeText(value string) string {
|
|
return truncate(Redact(value), 1024)
|
|
}
|
|
|
|
// Redact removes credentials, signed-URL parameters, UUIDs and object keys from
|
|
// free-form error text before it reaches stdout, logs or trace exception events.
|
|
func Redact(value string) string {
|
|
for _, pattern := range redactPatterns {
|
|
value = pattern.ReplaceAllString(value, "$1***")
|
|
}
|
|
return truncate(value, 1024)
|
|
}
|
|
|
|
func truncate(value string, limit int) string {
|
|
if len(value) <= limit {
|
|
return value
|
|
}
|
|
return value[:limit] + "..."
|
|
}
|