| 1 | |
| 2 | |
| 3 | package diagnostics |
| 4 | |
| 5 | import ( |
| 6 | "regexp" |
| 7 | "strings" |
| 8 | ) |
| 9 | |
| 10 | var patterns = []struct { |
| 11 | re *regexp.Regexp |
| 12 | replacement string |
| 13 | }{ |
| 14 | {regexp.MustCompile(`\x1b\[[0-?]*[ -/]*[@-~]`), ""}, |
| 15 | {regexp.MustCompile(`(?im)^(\s*(?:cookie|set-cookie|authorization|proxy-authorization)\s*[:=]).*$`), "${1} [redacted]"}, |
| 16 | {regexp.MustCompile(`(?is)-----BEGIN [^-]*(?:PRIVATE KEY|CERTIFICATE)-----.*?(?:-----END [^-]+-----|$)`), "[redacted key]"}, |
| 17 | {regexp.MustCompile(`(?i)\b[a-z][a-z0-9+.-]*://[^\s<>"'` + "`" + `]+`), "[url]"}, |
| 18 | {regexp.MustCompile(`(?i)\b(?:Bearer|Basic)\s+[a-z0-9._~+/=-]+`), "[redacted authorization]"}, |
| 19 | {regexp.MustCompile(`(?i)(["']?(?:password|passwd|pwd|token|access[_-]?token|refresh[_-]?token|id[_-]?token|api[_-]?key|apikey|secret|client[_-]?secret|authorization|proxy-authorization|cookie|set-cookie|auth|credential|subscription[_-]?url)["']?\s*[:=]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;}]+)`), "${1}[redacted]"}, |
| 20 | {regexp.MustCompile(`\b(?:sk-[A-Za-z0-9_-]{8,}|gh[pousr]_[A-Za-z0-9_]{12,}|github_pat_[A-Za-z0-9_]+|eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+)\b`), "[redacted token]"}, |
| 21 | {regexp.MustCompile(`\b[a-fA-F0-9]{32,}\b`), "[redacted id]"}, |
| 22 | {regexp.MustCompile(`(?i)[a-z]:[\\/][^\r\n"'<>:]+`), "[home path]"}, |
| 23 | {regexp.MustCompile(`(?i)/(?:Users|home|Volumes|mnt|media|private|tmp|var|opt|Applications|usr|etc|run)/[^\r\n"'<>:]+`), "[home path]"}, |
| 24 | {regexp.MustCompile(`[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}`), "[email]"}, |
| 25 | {regexp.MustCompile(`\b(?:[0-9]{1,3}\.){3}[0-9]{1,3}\b`), "[ip]"}, |
| 26 | } |
| 27 | |
| 28 | func Redact(s string) string { |
| 29 | for _, p := range patterns { |
| 30 | s = p.re.ReplaceAllString(s, p.replacement) |
| 31 | } |
| 32 | return strings.ToValidUTF8(s, "�") |
| 33 | } |