-
Notifications
You must be signed in to change notification settings - Fork 0
/
util.go
294 lines (253 loc) · 8.05 KB
/
util.go
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
package auth
import (
"bytes"
"context"
_ "embed"
"encoding/base64"
"errors"
"fmt"
"github.com/cloudbees-io/checkout/internal/helper"
"net/url"
"os"
"os/exec"
"path/filepath"
"regexp"
"runtime"
"strconv"
"strings"
"text/template"
"github.com/cloudbees-io/checkout/internal/git"
"gopkg.in/alessio/shellescape.v1"
)
const (
tokenPlaceholderConfigValue = "Authorization: Basic ***"
tokenConfigValue = "Authorization: Basic %s"
tokenConfigKey = "http.%s/.extraheader"
authTemplate = "x-access-token:%s"
)
//go:embed ssh_known_hosts.tmpl
var sshKnownHostsTemplate string
func noOpClean() error {
return nil
}
type TokenAuth struct {
Provider string
ScmToken string
ApiURL string
ApiToken string
}
func (a *TokenAuth) providerUsername() string {
switch a.Provider {
case "github":
// GHA checkout action uses this username
return "x-access-token"
case "gitlab":
// https://docs.gitlab.com/ee/user/project/settings/project_access_tokens.html
// Any non-blank value as a username
return "x-access-token"
case "bitbucket":
// this is what they suggest when you go through https://bitbucket.org/{org}/{repo}/admin/access-tokens
return "x-token-auth"
case "custom":
return "x-access-token"
default:
return "git"
}
}
func (a *TokenAuth) options() map[string][]string {
options := make(map[string][]string)
options["username"] = []string{a.providerUsername()}
if a.ScmToken != "" {
options["password"] = []string{base64.StdEncoding.EncodeToString([]byte(a.ScmToken))}
} else if a.ApiToken != "" && a.ApiURL != "" {
options["cloudBeesApiUrl"] = []string{a.ApiURL}
options["cloudBeesApiToken"] = []string{base64.StdEncoding.EncodeToString([]byte(a.ApiToken))}
}
return options
}
func ConfigureToken(cli *git.GitCLI, configPath string, globalConfig bool, serverURL string, token TokenAuth) (func() error, error) {
if configPath != "" && globalConfig {
return noOpClean, fmt.Errorf("unexpected ConfigureToken parameter combination")
}
if configPath == "" && !globalConfig {
configPath = filepath.Join(cli.Cwd(), ".git", "config")
}
var err error
if globalConfig {
if configPath, err = cli.GlobalConfigPath(); err != nil {
return noOpClean, err
}
}
helperCommand, cleaner, err := helper.InstallHelperFor(serverURL, token.options())
if err != nil {
return cleaner, err
}
oldHelper, _ := cli.GetConfig(globalConfig, "credential.helper")
oldUseHttpPath, _ := cli.GetConfig(globalConfig, "credential.useHttpPath")
fullCleaner := func() error {
var errs []error
if oldHelper == "" {
if _, err := cli.UnsetConfig(globalConfig, "credential.helper"); err != nil {
errs = append(errs, err)
}
} else if err := cli.SetConfigStr(globalConfig, "credential.helper", oldHelper); err != nil {
errs = append(errs, err)
}
useHttpPath, _ := strconv.ParseBool(oldUseHttpPath)
if oldUseHttpPath == "" {
if _, err := cli.UnsetConfig(globalConfig, "credential.useHttpPath"); err != nil {
errs = append(errs, err)
}
} else if err := cli.SetConfigBool(globalConfig, "credential.useHttpPath", useHttpPath); err != nil {
errs = append(errs, err)
}
if err := cleaner(); err != nil {
errs = append(errs, err)
}
if len(errs) > 0 {
return errors.Join(errs...)
}
return nil
}
if err := cli.SetConfigStr(globalConfig, "credential.helper", helperCommand); err != nil {
return fullCleaner, err
}
if err := cli.SetConfigBool(globalConfig, "credential.useHttpPath", true); err != nil {
return fullCleaner, err
}
return fullCleaner, nil
}
func ConfigureSubmoduleTokenAuth(cli *git.GitCLI, recursive bool, serverURL string, token string) error {
u, err := url.Parse(serverURL)
if err != nil {
return err
}
key := fmt.Sprintf(tokenConfigKey, u.Scheme+"://"+u.Host)
output, err := cli.SubmoduleForeach(recursive, "sh", "-c", fmt.Sprintf(`%s config --local '%s' '%s' && %s config --local --show-origin --name-only --get-regexp remote.origin.url`, cli.Executable(), key, tokenPlaceholderConfigValue, cli.Executable()))
if err != nil {
return err
}
auth := base64.StdEncoding.EncodeToString([]byte(fmt.Sprintf(authTemplate, token)))
configPathRegex := regexp.MustCompile(`^file:([^\t]+)\tremote\.origin\.url$`)
for _, line := range strings.Split(output, "\n") {
matches := configPathRegex.FindStringSubmatch(line)
if matches == nil {
continue
}
configPath := matches[1]
if configPath != "" {
if !filepath.IsAbs(configPath) {
configPath = filepath.Join(cli.Cwd(), configPath)
}
if err := replaceTokenPlaceholder(configPath, auth); err != nil {
return err
}
}
}
return nil
}
func replaceTokenPlaceholder(configPath string, token string) error {
stat, err := os.Stat(configPath)
if err != nil {
return fmt.Errorf("could not find file '%s': %v", configPath, err)
}
content, err := os.ReadFile(configPath)
if err != nil {
return err
}
placeholdeReplacement := fmt.Sprintf(tokenConfigValue, token)
content = bytes.ReplaceAll(content, []byte(tokenPlaceholderConfigValue), []byte(placeholdeReplacement))
return os.WriteFile(configPath, content, stat.Mode())
}
func GenerateSSHKey(ctx context.Context, tempDir string, prefix string, inputKey string) (string, error) {
if err := os.MkdirAll(tempDir, os.ModePerm); err != nil {
return "", err
}
keyPath := filepath.Join(tempDir, prefix+"_key")
if err := os.WriteFile(keyPath, []byte(inputKey), 0600); err != nil {
return "", err
}
if runtime.GOOS == "windows" {
// remove inherited permissions on windows
icacls, err := exec.LookPath("icacls.exe")
if err != nil && !errors.Is(err, exec.ErrDot) {
return "", fmt.Errorf("cannot find icacls.exe: %v", err)
} else if errors.Is(err, exec.ErrDot) {
if icacls, err = filepath.Abs(icacls); err != nil {
return "", fmt.Errorf("cannot find icacls.exe: %v", err)
}
}
c := exec.CommandContext(ctx, icacls, keyPath, "/grant:r", os.Getenv("USERDOMAIN")+"\\"+os.Getenv("USERNAME")+":F")
c.Dir = os.Getenv(tempDir)
if err = c.Start(); err != nil {
return "", err
}
if err = c.Wait(); err != nil {
return "", err
}
c = exec.CommandContext(ctx, icacls, keyPath, "/inheritance:r")
c.Dir = os.Getenv(tempDir)
if err = c.Start(); err != nil {
return "", err
}
if err = c.Wait(); err != nil {
return "", err
}
}
return keyPath, nil
}
func GenerateSSHCommand(sshKeyPath string, sshStrict bool, sshKnownHostsPath string) (string, error) {
ssh, err := exec.LookPath("ssh")
if err != nil && !errors.Is(err, exec.ErrDot) {
return "", fmt.Errorf("cannot find ssh: %v", err)
} else if errors.Is(err, exec.ErrDot) {
if ssh, err = filepath.Abs(ssh); err != nil {
return "", fmt.Errorf("cannot find ssh: %v", err)
}
}
cmd := fmt.Sprintf("%s -i %s", shellescape.Quote(ssh), shellescape.Quote(sshKeyPath))
if sshStrict {
cmd = cmd + " -o StrictHostKeyChecking=yes -o CheckHostIP=no"
}
cmd = cmd + " -o UserKnownHostsFile=$RUNNER_TEMP/" + filepath.Base(sshKnownHostsPath)
return cmd, nil
}
func GenerateSSHKnownHosts(home string, tempDir string, prefix string, inputKnownHosts string) (_ string, retErr error) {
tmpl := template.New("ssh_known_hosts")
tmpl, err := tmpl.Parse(sshKnownHostsTemplate)
if err != nil {
return "", err
}
userKnownHostsPath := filepath.Join(home, ".ssh", "known_hosts")
userKnownHosts := ""
if info, err := os.Stat(userKnownHostsPath); err == nil && !info.IsDir() {
if bytes, err := os.ReadFile(userKnownHostsPath); err == nil {
userKnownHosts = string(bytes)
}
// if we couldn't read it, treat it as an empty file
}
if err := os.MkdirAll(tempDir, os.ModePerm); err != nil {
return "", err
}
knownHostsPath := filepath.Join(tempDir, prefix+"_known_hosts")
f, err := os.Create(knownHostsPath)
if err != nil {
return "", err
}
defer func(f *os.File) {
err := f.Close()
if err != nil && retErr == nil {
retErr = err
}
}(f)
err = tmpl.Execute(f, struct {
UserKnownHosts string
UserKnownHostsPath string
SSHKnownHosts string
}{
UserKnownHosts: userKnownHosts,
UserKnownHostsPath: userKnownHostsPath,
SSHKnownHosts: inputKnownHosts,
})
return knownHostsPath, err
}