Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix(git): add warning of the mismatch of git cred and url #3136

Merged
merged 1 commit into from
Sep 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions pkg/git/git.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ import (
"os"
"os/exec"
"path/filepath"
"regexp"
"strconv"
"strings"

Expand All @@ -33,6 +34,11 @@ const (
sshMissingKnownHostsSSHCommand = "ssh -o StrictHostKeyChecking=accept-new"
)

var (
// sshURLRegexFormat matches the url of SSH git repository
sshURLRegexFormat = regexp.MustCompile(`(ssh://[\w\d\.]+|.+@?.+\..+:)(:[\d]+){0,1}/*(.*)`)
)

func run(logger *zap.SugaredLogger, dir string, args ...string) (string, error) {
c := exec.Command("git", args...)
var output bytes.Buffer
Expand Down Expand Up @@ -69,6 +75,7 @@ func Fetch(logger *zap.SugaredLogger, spec FetchSpec) error {
if err := ensureHomeEnv(logger); err != nil {
return err
}
validateGitAuth(logger, spec.URL)

if spec.Path != "" {
if _, err := run(logger, "", "init", spec.Path); err != nil {
Expand Down Expand Up @@ -244,3 +251,25 @@ func userHasKnownHostsFile(logger *zap.SugaredLogger) (bool, error) {
f.Close()
return true, nil
}

func validateGitAuth(logger *zap.SugaredLogger, url string) {
homeenv := os.Getenv("HOME")
sshCred := true
if _, err := os.Stat(homeenv + "/.ssh"); os.IsNotExist(err) {
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thinking about this some more I'm not sure this is enough to correctly validate SSH credentials. A user can mix SSH and non-SSH git credentials in a single Step. For example, with two Secrets:

apiVersion: v1
kind: Secret
metadata:
  name: example-gitlab-creds
  annotations:
    tekton.dev/git-0: https://gitlab.com
type: kubernetes.io/basic-auth
stringData:
  username: myuser
  password: hunter2
---
apiVersion: v1
kind: Secret
metadata:
  name: example-github-creds
  annotations:
    tekton.dev/git-0: github.com
type: kubernetes.io/ssh-auth
stringData:
  ssh-privatekey: blahblahblah
---
apiVersion: v1
kind: ServiceAccount
metadata:
  name: example-service-account
secrets:
  - name: example-gitlab-creds
  - name: example-github-creds
---
apiVersion: tekton.dev/v1beta1
kind: TaskRun
metadata:
  name: foobar
spec:
  serviceAccountName: example-service-account
  taskSpec:
    steps:
    - name: wait
      image: alpine:latest
      script: |
        echo "foo"

In this example YAML both a ~/.ssh directory and a ~/.git-credentials file will exist side by side. ~/.git-credentials is created for the gitlab Secret. So this code will print a warning because the gitlab basic auth URL is not SSH-formatted. But the user never intends to use SSH auth with a gitlab URL.

The full solution to this problem is probably quite a lot more complicated - it would need to read the ~/.ssh/config file and figure out whether the given url is intended to be used with SSH authentication.

We could work around this somewhat by updating the warning messages to be more relaxed. Something like:

logger.Warnf("SSH credentials have been provided but the URL %q is not a valid SSH URL", url)

But this feels like it would lead to more user confusion and I don't think this is a great workaround either.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I met the similar problem when I tested the code: if the given URL is a public repo and the cred is SSH type, the warning log will be shown and the pod can still pull the code successfully.
But it will be more too complex if we check the URL is public or not. So my point is we can just let the warning show since it's only a warning and people will not care about the warning if the job success. 🤔 WDYT?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hrm, tricky problem! OK, I think we can make this work with an even longer log message:

SSH credentials have been provided but the URL %q is not a valid SSH URL. This warning can be safely ignored if the URL is for a public repo or you are using basic auth

@vdemeester what do you think of this? Is it too vague? The other thing we could do is drop this message and only print a warning if a URL is definitely an SSH url but the user has 0 SSH credentials available in the Step. That is 100% of the time a legitimate error I think?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll change the message first but I'm also not quite sure that if we need that message when SSH credentials are provided but the URL is non-SSH. Let me know if there is better solutions!

sshCred = false
}
urlSSHFormat := ValidateGitSSHURLFormat(url)
if sshCred && !urlSSHFormat {
logger.Warnf("SSH credentials have been provided but the URL(%q) is not a valid SSH URL. This warning can be safely ignored if the URL is for a public repo or you are using basic auth", url)
} else if !sshCred && urlSSHFormat {
logger.Warnf("URL(%q) appears to need SSH authentication but no SSH credentials have been provided", url)
}
}

// ValidateGitSSHURLFormat validates the given URL format is SSH or not
func ValidateGitSSHURLFormat(url string) bool {
if sshURLRegexFormat.MatchString(url) {
return true
}
return false
}
105 changes: 105 additions & 0 deletions pkg/git/git_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
/*
Copyright 2020 The Tekton Authors

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package git

import "testing"

func TestValidateGitSSHURLFormat(t *testing.T) {
tests := []struct {
url string
want bool
}{
{
url: "git@github.com:user/project.git",
want: true,
},
{
url: "git@127.0.0.1:user/project.git",
want: true,
},
{
url: "http://github.com/user/project.git",
want: false,
},
{
url: "https://github.com/user/project.git",
want: false,
},
{
url: "http://127.0.0.1/user/project.git",
want: false,
},
{
url: "https://127.0.0.1/user/project.git",
want: false,
},
{
url: "http://host.xz/path/to/repo.git/",
want: false,
},
{
url: "https://host.xz/path/to/repo.git/",
want: false,
},
{
url: "ssh://user@host.xz:port/path/to/repo.git/",
want: true,
},
{
url: "ssh://user@host.xz/path/to/repo.git/",
want: true,
},
{
url: "ssh://host.xz:port/path/to/repo.git/",
want: true,
},
{
url: "ssh://host.xz/path/to/repo.git/",
want: true,
},
{
url: "git://host.xz/path/to/repo.git/",
want: false,
},
{
url: "/path/to/repo.git/",
want: false,
},
{
url: "file://~/path/to/repo.git/",
want: false,
},
{
url: "user@host.xz:/path/to/repo.git/",
want: true,
},
{
url: "host.xz:/path/to/repo.git/",
want: true,
},
{
url: "user@host.xz:path/to/repo.git",
want: true,
},
}

for _, tt := range tests {
got := ValidateGitSSHURLFormat(tt.url)
if got != tt.want {
t.Errorf("Validate URL(%v)'s SSH format got %v, want %v", tt.url, got, tt.want)
}
}
}