2022-05-10 19:54:40 +00:00
|
|
|
// Copyright 2020-2022 the Pinniped contributors. All Rights Reserved.
|
2020-10-22 15:30:51 +00:00
|
|
|
// SPDX-License-Identifier: Apache-2.0
|
|
|
|
|
2021-06-22 15:23:19 +00:00
|
|
|
package testlib
|
2020-10-22 15:30:51 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"io"
|
2021-04-15 14:59:38 +00:00
|
|
|
"net/url"
|
2020-10-22 15:30:51 +00:00
|
|
|
"regexp"
|
2020-12-02 21:43:17 +00:00
|
|
|
"strings"
|
2020-10-22 15:30:51 +00:00
|
|
|
"testing"
|
|
|
|
)
|
|
|
|
|
|
|
|
// NewLoggerReader wraps an io.Reader to log its input and output. It also performs some heuristic token masking.
|
|
|
|
func NewLoggerReader(t *testing.T, name string, reader io.Reader) io.Reader {
|
|
|
|
t.Helper()
|
|
|
|
return &testlogReader{t: t, name: name, r: reader}
|
|
|
|
}
|
|
|
|
|
|
|
|
type testlogReader struct {
|
|
|
|
t *testing.T
|
|
|
|
name string
|
|
|
|
r io.Reader
|
|
|
|
}
|
|
|
|
|
|
|
|
func (l *testlogReader) Read(p []byte) (n int, err error) {
|
|
|
|
l.t.Helper()
|
|
|
|
n, err = l.r.Read(p)
|
|
|
|
if err != nil {
|
2020-12-02 21:43:17 +00:00
|
|
|
l.t.Logf("%s > %q: %v", l.name, MaskTokens(string(p[0:n])), err)
|
2020-10-22 15:30:51 +00:00
|
|
|
} else {
|
2020-12-02 21:43:17 +00:00
|
|
|
l.t.Logf("%s > %q", l.name, MaskTokens(string(p[0:n])))
|
2020-10-22 15:30:51 +00:00
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2020-12-02 21:43:17 +00:00
|
|
|
// MaskTokens makes a best-effort attempt to mask out things that look like secret tokens in test output.
|
2022-05-10 19:54:40 +00:00
|
|
|
// Provides more readable test output, but also obscures sensitive state params and authcodes from public test output.
|
2020-12-02 21:43:17 +00:00
|
|
|
func MaskTokens(in string) string {
|
|
|
|
var tokenLike = regexp.MustCompile(`(?mi)[a-zA-Z0-9._-]{30,}|[a-zA-Z0-9]{20,}`)
|
|
|
|
return tokenLike.ReplaceAllStringFunc(in, func(t string) string {
|
|
|
|
// This is a silly heuristic, but things with multiple dots are more likely hostnames that we don't want masked.
|
|
|
|
if strings.Count(t, ".") >= 4 {
|
|
|
|
return t
|
|
|
|
}
|
2021-03-23 17:07:34 +00:00
|
|
|
// Another heuristic, things that start with "--" are probably CLI flags.
|
|
|
|
if strings.HasPrefix(t, "--") {
|
|
|
|
return t
|
|
|
|
}
|
2020-10-22 15:30:51 +00:00
|
|
|
return fmt.Sprintf("[...%d bytes...]", len(t))
|
|
|
|
})
|
|
|
|
}
|
2021-04-15 14:59:38 +00:00
|
|
|
|
|
|
|
// Remove any potentially sensitive query param and fragment values for test logging.
|
|
|
|
func RedactURLParams(fullURL *url.URL) string {
|
|
|
|
copyOfURL, _ := url.Parse(fullURL.String())
|
|
|
|
if len(copyOfURL.RawQuery) > 0 {
|
|
|
|
copyOfURL.RawQuery = "redacted"
|
|
|
|
}
|
|
|
|
if len(copyOfURL.Fragment) > 0 {
|
|
|
|
copyOfURL.Fragment = "redacted"
|
|
|
|
}
|
|
|
|
return copyOfURL.String()
|
|
|
|
}
|