Skip to content

Commit

Permalink
Redact git secret from logs (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
simongottschlag authored Mar 1, 2023
1 parent d1fb84f commit f5e7ce8
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 2 deletions.
26 changes: 24 additions & 2 deletions src/source/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/url"
"os"
"path/filepath"
"strings"

"github.com/fluxcd/pkg/git"
"github.com/fluxcd/pkg/git/gogit"
Expand Down Expand Up @@ -81,8 +82,9 @@ func (s *GitSource) checkout(ctx context.Context) (*map[string][]byte, string, e
}
commit, err := gitReader.Clone(ctx, s.cfg.GitUrl, cloneOpts)
if err != nil {
log.V(1).Error(err, "failed to clone")
return nil, "", err
redactedErr := redactGitSecretFromError(s.cfg.GitUrl, err)
log.V(1).Error(redactedErr, "failed to clone")
return nil, "", redactedErr
}

log.V(1).Info("commit data", "ShortMessage", commit.ShortMessage(), "String", commit.String(), "commit", commit)
Expand All @@ -108,6 +110,26 @@ func (s *GitSource) checkout(ctx context.Context) (*map[string][]byte, string, e
return yamlFiles, revision, nil
}

func redactGitSecretFromError(gitUrl string, inputErr error) error {
parsedGitUrl, err := url.Parse(gitUrl)
if err != nil {
return inputErr
}

gitSecret, ok := parsedGitUrl.User.Password()
if !ok {
return inputErr
}

if gitSecret == "" {
return inputErr
}

inputErrString := inputErr.Error()
inputErrStringRedacted := strings.ReplaceAll(inputErrString, gitSecret, "redacted")
return fmt.Errorf(inputErrStringRedacted)
}

func createTemporaryDirectory(ctx context.Context, path string) (string, func(), error) {
log := logr.FromContextOrDiscard(ctx)

Expand Down
27 changes: 27 additions & 0 deletions src/source/git_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -164,3 +164,30 @@ func testCommitFile(t *testing.T, ctx context.Context, ggc *gg.Client, path, con

return newRef, nil
}

func TestRedactGitSecretFromError(t *testing.T) {
cases := []struct {
testDescription string
gitUrl string
inputErrorString string
expectedResult string
}{
{
testDescription: "redact secret",
// secretlint-disable
gitUrl: "https://foo:supersecret@foobar.net",
// secretlint-disable
inputErrorString: "unable to clone https://foo:supersecret@foobar.net",
// secretlint-disable
expectedResult: "unable to clone https://foo:redacted@foobar.net",
},
}

for i, c := range cases {
t.Logf("Test #%d: %s", i, c.testDescription)
inputError := fmt.Errorf(c.inputErrorString)
result := redactGitSecretFromError(c.gitUrl, inputError)
require.Equal(t, c.expectedResult, result.Error())
}

}

0 comments on commit f5e7ce8

Please sign in to comment.