package runnerproto import ( "regexp" "strings" "unicode" "unicode/utf8" ) // DetailLimit bounds an error's words in a log line or a step report. const DetailLimit = 500 var ( // A header that carries a credential, its value (and scheme) gone. detailHeader = regexp.MustCompile(`(?i)\b((?:proxy-)?authorization|set-cookie|cookie|x-api-key|private-token)(["']?\s*[:=]\s*["']?)(?:(?:bearer|basic|token|digest|negotiate)\s+)?[^\s,;"']+`) // A URL's userinfo (user:password@). detailUserinfo = regexp.MustCompile(`(?i)\b([a-z][a-z0-9+.-]*://)[^/\s@?#'"]+@`) // A JSON member whose name says it holds a credential. detailJSONKey = regexp.MustCompile(`(?i)("[a-z0-9_-]*(?:token|secret|password|passwd|api[_-]?key|authorization|credentials?)"\s*:\s*")[^"]*"`) // A JSON web token, and any long opaque run (a hub token is 64 hex; // a commit SHA-1, 40, is kept). detailJWT = regexp.MustCompile(`\beyJ[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]{4,}\.[A-Za-z0-9_-]*`) detailOpaque = regexp.MustCompile(`\b[A-Za-z0-9_+]{41,}=*`) detailSpace = regexp.MustCompile(`\s+`) ) // RedactDetail is an error's words made safe to log or report: no // credential (bearer and basic values, Authorization and cookie headers, // URL userinfo, credential-named JSON members, known token prefixes, // JSON web tokens, long opaque runs), one line without control or // format characters, backticks as quotes (it may sit in a code block), // and at most limit bytes, the cut marked. Redaction runs before the // cut, so a credential across the bound is never half shown. func RedactDetail(s string, limit int) string { s = strings.ToValidUTF8(s, "?") s = strings.Map(func(r rune) rune { if unicode.IsControl(r) || unicode.Is(unicode.Cf, r) { return ' ' } if r == '`' { return '\'' } return r }, s) s = detailHeader.ReplaceAllString(s, "${1}${2}***") s = detailUserinfo.ReplaceAllString(s, "${1}***@") s = detailJSONKey.ReplaceAllString(s, `${1}***"`) s = detailJWT.ReplaceAllString(s, "***") s = RedactText(s, nil) s = detailOpaque.ReplaceAllString(s, "***") s = strings.TrimSpace(detailSpace.ReplaceAllString(s, " ")) if len(s) <= limit { return s } mark := "…" if limit < len(mark) { mark = "" } s = s[:max(limit-len(mark), 0)] for !utf8.ValidString(s) { s = s[:len(s)-1] } return s + mark }