improve logging
All checks were successful
continuous-integration/drone/push Build is passing

This commit is contained in:
2026-02-11 11:24:27 +11:00
parent 34ac9287b4
commit f1be31781c
3 changed files with 110 additions and 22 deletions

View File

@@ -6,11 +6,18 @@ import (
"log/slog"
"os"
"path/filepath"
"regexp"
"strings"
"vctp/internal/utils"
"gopkg.in/yaml.v2"
)
var (
postgresURIUserInfoPasswordPattern = regexp.MustCompile(`(?i)(postgres(?:ql)?://[^@/\s]*:)([^@/\s]*)(@)`)
postgresKVPasswordPattern = regexp.MustCompile(`(?i)(\bpassword\s*=\s*)(?:'[^']*'|"[^"]*"|[^\s]+)`)
)
type Settings struct {
SettingsPath string
Logger *slog.Logger
@@ -102,12 +109,24 @@ func (s *Settings) ReadYMLSettings() error {
if redacted.Settings.EncryptionKey != "" {
redacted.Settings.EncryptionKey = "REDACTED"
}
if redacted.Settings.DatabaseURL != "" {
redacted.Settings.DatabaseURL = redactDatabaseURL(redacted.Settings.DatabaseURL)
}
s.Logger.Debug("Updating settings", "settings", redacted)
s.Values = &settings
return nil
}
func redactDatabaseURL(databaseURL string) string {
if strings.TrimSpace(databaseURL) == "" {
return databaseURL
}
redacted := postgresURIUserInfoPasswordPattern.ReplaceAllString(databaseURL, `${1}REDACTED${3}`)
redacted = postgresKVPasswordPattern.ReplaceAllString(redacted, `${1}REDACTED`)
return redacted
}
func (s *Settings) WriteYMLSettings() error {
if s.Values == nil {
return errors.New("settings are not loaded")

View File

@@ -0,0 +1,29 @@
package settings
import "testing"
func TestRedactDatabaseURL_PostgresURI(t *testing.T) {
input := "postgres://vctp_user:Secr3tP%40ss@db-host:5432/vctp?sslmode=disable"
got := redactDatabaseURL(input)
want := "postgres://vctp_user:REDACTED@db-host:5432/vctp?sslmode=disable"
if got != want {
t.Fatalf("unexpected redaction result\nwant: %s\ngot: %s", want, got)
}
}
func TestRedactDatabaseURL_PostgresKeyValue(t *testing.T) {
input := "host=db-host port=5432 dbname=vctp user=vctp_user password='P@ss:w0rd#%' sslmode=disable"
got := redactDatabaseURL(input)
want := "host=db-host port=5432 dbname=vctp user=vctp_user password=REDACTED sslmode=disable"
if got != want {
t.Fatalf("unexpected redaction result\nwant: %s\ngot: %s", want, got)
}
}
func TestRedactDatabaseURL_UnchangedWhenNoPassword(t *testing.T) {
input := "host=db-host port=5432 dbname=vctp user=vctp_user sslmode=disable"
got := redactDatabaseURL(input)
if got != input {
t.Fatalf("expected input to remain unchanged\nwant: %s\ngot: %s", input, got)
}
}