Skip to content

Commit

Permalink
Remove user credentials specified in the Git origin URL (#1494)
Browse files Browse the repository at this point in the history
## Changes
We set the origin URL as metadata in any jobs created by DABs. This PR
makes sure user credentials do not leak into the set metadata in the
job.
 
## Tests
Unit test

---------

Co-authored-by: Pieter Noordhuis <pieter.noordhuis@databricks.com>
  • Loading branch information
shreyas-goenka and pietern authored Jun 17, 2024
1 parent 44e3928 commit ac6b80e
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
18 changes: 17 additions & 1 deletion libs/git/repository.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"io/fs"
"net/url"
"path"
"path/filepath"
"strings"
Expand Down Expand Up @@ -100,7 +101,22 @@ func (r *Repository) LatestCommit() (string, error) {

// return origin url if it's defined, otherwise an empty string
func (r *Repository) OriginUrl() string {
return r.config.variables["remote.origin.url"]
rawUrl := r.config.variables["remote.origin.url"]

// Remove username and password from the URL.
parsedUrl, err := url.Parse(rawUrl)
if err != nil {
// Git supports https URLs and non standard URLs like "ssh://" or "file://".
// Parsing these URLs is not supported by the Go standard library. In case
// of an error, we return the raw URL. This is okay because for ssh URLs
// because passwords cannot be included in the URL.
return rawUrl
}
// Setting User to nil removes the username and password from the URL when
// .String() is called.
// See: https://pkg.go.dev/net/url#URL.String
parsedUrl.User = nil
return parsedUrl.String()
}

// loadConfig loads and combines user specific and repository specific configuration files.
Expand Down
6 changes: 6 additions & 0 deletions libs/git/repository_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -207,3 +207,9 @@ func TestRepositoryGitConfigWhenNotARepo(t *testing.T) {
originUrl := repo.OriginUrl()
assert.Equal(t, "", originUrl)
}

func TestRepositoryOriginUrlRemovesUserCreds(t *testing.T) {
repo := newTestRepository(t)
repo.addOriginUrl("https://username:token@github.com/databricks/foobar.git")
repo.assertOriginUrl("https://github.com/databricks/foobar.git")
}

0 comments on commit ac6b80e

Please sign in to comment.