| 1 | package git |
| 2 | |
| 3 | import ( |
| 4 | "encoding/json" |
| 5 | "fmt" |
| 6 | |
| 7 | "github.com/go-git/go-git/v6/plumbing/transport" |
| 8 | githttp "github.com/go-git/go-git/v6/plumbing/transport/http" |
| 9 | gitssh "github.com/go-git/go-git/v6/plumbing/transport/ssh" |
| 10 | xssh "golang.org/x/crypto/ssh" |
| 11 | ) |
| 12 | |
| 13 | // AuthMethodFromCredential builds a transport.AuthMethod from credential type and JSON data. |
| 14 | func AuthMethodFromCredential(credType, data string) (transport.AuthMethod, error) { |
| 15 | switch credType { |
| 16 | case "basic": |
| 17 | var cred struct { |
| 18 | Username string `json:"username"` |
| 19 | Password string `json:"password"` |
| 20 | } |
| 21 | if err := json.Unmarshal([]byte(data), &cred); err != nil { |
| 22 | return nil, fmt.Errorf("parse basic credential: %w", err) |
| 23 | } |
| 24 | return &githttp.BasicAuth{ |
| 25 | Username: cred.Username, |
| 26 | Password: cred.Password, |
| 27 | }, nil |
| 28 | |
| 29 | case "token": |
| 30 | var cred struct { |
| 31 | Token string `json:"token"` |
| 32 | } |
| 33 | if err := json.Unmarshal([]byte(data), &cred); err != nil { |
| 34 | return nil, fmt.Errorf("parse token credential: %w", err) |
| 35 | } |
| 36 | return &githttp.TokenAuth{ |
| 37 | Token: cred.Token, |
| 38 | }, nil |
| 39 | |
| 40 | case "ssh": |
| 41 | var cred struct { |
| 42 | Key string `json:"key"` |
| 43 | Password string `json:"password"` |
| 44 | } |
| 45 | if err := json.Unmarshal([]byte(data), &cred); err != nil { |
| 46 | return nil, fmt.Errorf("parse ssh credential: %w", err) |
| 47 | } |
| 48 | auth, err := gitssh.NewPublicKeys("git", []byte(cred.Key), cred.Password) |
| 49 | if err != nil { |
| 50 | return nil, fmt.Errorf("create ssh auth: %w", err) |
| 51 | } |
| 52 | // Trust all hosts — server-side, we trust configured repos. |
| 53 | auth.HostKeyCallback = xssh.InsecureIgnoreHostKey() |
| 54 | return auth, nil |
| 55 | |
| 56 | default: |
| 57 | return nil, fmt.Errorf("unknown credential type: %q", credType) |
| 58 | } |
| 59 | } |
| 60 | |