Improve ssh handling (#277)

checkout: use configured protocol for PR checkout

instead of defaulting to ssh if that is enabled
this might fix #262

login add: try to find a matching ssh key & store it in config

possibly expensive operation should be done once

pr checkout: don't fetch ssh keys

As a result, we don't try to pull via ssh, if no privkey was configured.
This increases chances of a using ssh only on a working ssh setup.

fix import order

remove debug print statement

improve ssh-key value docs

rm named return & fix pwCallback nil check

Co-authored-by: Norwin Roosen <git@nroo.de>
Co-authored-by: 6543 <6543@obermui.de>
Reviewed-on: https://gitea.com/gitea/tea/pulls/277
Reviewed-by: khmarbaise <khmarbaise@noreply.gitea.io>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Reviewed-by: 6543 <6543@obermui.de>
Co-Authored-By: Norwin <noerw@noreply.gitea.io>
Co-Committed-By: Norwin <noerw@noreply.gitea.io>
This commit is contained in:
Norwin
2020-12-11 21:42:41 +08:00
committed by 6543
parent 7e191eb18b
commit 0f38da068c
6 changed files with 93 additions and 24 deletions

View File

@ -22,29 +22,26 @@ type pwCallback = func(string) (string, error)
// GetAuthForURL returns the appropriate AuthMethod to be used in Push() / Pull()
// operations depending on the protocol, and prompts the user for credentials if
// necessary.
func GetAuthForURL(remoteURL *url.URL, authToken, keyFile string, passwordCallback pwCallback) (auth git_transport.AuthMethod, err error) {
func GetAuthForURL(remoteURL *url.URL, authToken, keyFile string, passwordCallback pwCallback) (git_transport.AuthMethod, error) {
switch remoteURL.Scheme {
case "http", "https":
// gitea supports push/pull via app token as username.
auth = &gogit_http.BasicAuth{Password: "", Username: authToken}
return &gogit_http.BasicAuth{Password: "", Username: authToken}, nil
case "ssh":
// try to select right key via ssh-agent. if it fails, try to read a key manually
user := remoteURL.User.Username()
auth, err = gogit_ssh.DefaultAuthBuilder(user)
if err != nil && passwordCallback != nil {
auth, err := gogit_ssh.DefaultAuthBuilder(user)
if err != nil {
signer, err2 := readSSHPrivKey(keyFile, passwordCallback)
if err2 != nil {
return nil, err2
}
auth = &gogit_ssh.PublicKeys{User: user, Signer: signer}
}
default:
return nil, fmt.Errorf("don't know how to handle url scheme %v", remoteURL.Scheme)
return auth, nil
}
return
return nil, fmt.Errorf("don't know how to handle url scheme %v", remoteURL.Scheme)
}
func readSSHPrivKey(keyFile string, passwordCallback pwCallback) (sig ssh.Signer, err error) {
@ -61,7 +58,7 @@ func readSSHPrivKey(keyFile string, passwordCallback pwCallback) (sig ssh.Signer
return nil, err
}
sig, err = ssh.ParsePrivateKey(sshKey)
if _, ok := err.(*ssh.PassphraseMissingError); ok {
if _, ok := err.(*ssh.PassphraseMissingError); ok && passwordCallback != nil {
// allow for up to 3 password attempts
for i := 0; i < 3; i++ {
var pass string