-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanager.go
More file actions
167 lines (146 loc) · 4.66 KB
/
Copy pathmanager.go
File metadata and controls
167 lines (146 loc) · 4.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
package git
import (
"context"
"fmt"
"os"
"path/filepath"
"github.com/functions-dev/func-operator/internal/monitoring"
"github.com/go-git/go-git/v6"
"github.com/go-git/go-git/v6/plumbing"
"github.com/go-git/go-git/v6/plumbing/client"
"github.com/go-git/go-git/v6/plumbing/transport"
"github.com/go-git/go-git/v6/plumbing/transport/http"
gitssh "github.com/go-git/go-git/v6/plumbing/transport/ssh"
"github.com/prometheus/client_golang/prometheus"
gossh "golang.org/x/crypto/ssh"
)
const (
cloneBaseDir = "/git-repos"
)
type Manager interface {
CloneRepository(ctx context.Context, url, subPath, reference string, auth map[string][]byte) (*Repository, error)
}
func NewManager() (Manager, error) {
if err := os.MkdirAll(cloneBaseDir, 0755); err != nil {
return nil, fmt.Errorf("failed to create git clone base directory: %w", err)
}
// go-git's SSH transport requires a known_hosts file for host key algorithm
// discovery, even when HostKeyCallback is already set. Without this file,
// SSH connections fail in containers that lack ~/.ssh/known_hosts.
if err := ensureKnownHostsExists(); err != nil {
return nil, fmt.Errorf("failed to ensure known_hosts exists: %w", err)
}
return &managerImpl{}, nil
}
type managerImpl struct{}
func (m *managerImpl) CloneRepository(ctx context.Context, repoUrl, subPath, reference string, auth map[string][]byte) (*Repository, error) {
timer := prometheus.NewTimer(monitoring.GitCloneDuration)
defer timer.ObserveDuration()
parsedURL, err := transport.ParseURL(repoUrl)
if err != nil {
return nil, fmt.Errorf("failed to parse repository URL: %w", err)
}
targetDir, err := os.MkdirTemp(cloneBaseDir, "repo-*")
if err != nil {
return nil, fmt.Errorf("failed to create temporary directory: %w", err)
}
clientOpts, tempFile := m.getClientOptions(parsedURL.Scheme, auth)
repo, err := git.PlainCloneContext(ctx, targetDir, &git.CloneOptions{
URL: repoUrl,
ReferenceName: plumbing.ReferenceName(reference),
SingleBranch: true,
Depth: 1,
ClientOptions: clientOpts,
})
if err != nil {
return nil, fmt.Errorf("failed to clone repo: %w", err)
}
head, err := repo.Head()
if err != nil {
return nil, fmt.Errorf("failed to find head: %w", err)
}
result := &Repository{
CloneDir: targetDir,
SubPath: subPath,
Commit: head.Hash().String(),
Branch: reference,
}
result.AddTempFile(tempFile)
return result, nil
}
func (m *managerImpl) getClientOptions(scheme string, authSecret map[string][]byte) ([]client.Option, string) {
if scheme == "ssh" {
return m.getSSHClientOptions(authSecret)
}
return m.getHTTPClientOptions(authSecret), ""
}
func (m *managerImpl) getHTTPClientOptions(authSecret map[string][]byte) []client.Option {
if len(authSecret) == 0 {
return nil
} else if token, ok := authSecret["token"]; ok {
return []client.Option{
client.WithHTTPAuth(&http.BasicAuth{
Username: "empty", // can be anything except an empty string
Password: string(token),
}),
}
} else if username, ok := authSecret["username"]; ok {
if password, ok := authSecret["password"]; ok {
return []client.Option{
client.WithHTTPAuth(&http.BasicAuth{
Username: string(username),
Password: string(password),
}),
}
}
return nil
}
return nil
}
func ensureKnownHostsExists() error {
home, err := os.UserHomeDir()
if err != nil {
return err
}
sshDir := filepath.Join(home, ".ssh")
if err := os.MkdirAll(sshDir, 0700); err != nil {
return err
}
knownHostsPath := filepath.Join(sshDir, "known_hosts")
if _, err := os.Stat(knownHostsPath); os.IsNotExist(err) {
return os.WriteFile(knownHostsPath, nil, 0644)
}
return nil
}
func (m *managerImpl) getSSHClientOptions(authSecret map[string][]byte) ([]client.Option, string) {
privateKey, hasKey := authSecret["sshPrivateKey"]
if !hasKey {
return []client.Option{
client.WithSSHAuth(&gitssh.Password{
User: "git",
HostKeyCallbackHelper: gitssh.HostKeyCallbackHelper{HostKeyCallback: gossh.InsecureIgnoreHostKey()},
}),
}, ""
}
password := string(authSecret["sshPrivateKeyPassword"])
auth, err := gitssh.NewPublicKeys("git", privateKey, password)
if err != nil {
return nil, ""
}
auth.HostKeyCallback = gossh.InsecureIgnoreHostKey()
var tempFilePath string
if knownHostsData, ok := authSecret["known_hosts"]; ok {
tmpFile, err := os.CreateTemp("", "known_hosts-*")
if err == nil {
if _, err := tmpFile.Write(knownHostsData); err == nil {
_ = tmpFile.Close()
tempFilePath = tmpFile.Name()
cb, err := gitssh.NewKnownHostsCallback(tempFilePath)
if err == nil {
auth.HostKeyCallback = cb
}
}
}
}
return []client.Option{client.WithSSHAuth(auth)}, tempFilePath
}