-
Notifications
You must be signed in to change notification settings - Fork 542
Expand file tree
/
Copy pathconfig.go
More file actions
265 lines (221 loc) · 6.82 KB
/
config.go
File metadata and controls
265 lines (221 loc) · 6.82 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
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
package ssh
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"github.com/loft-sh/devpod/pkg/util"
"github.com/loft-sh/log"
"github.com/loft-sh/log/scanner"
"github.com/pkg/errors"
)
var configLock sync.Mutex
var (
MarkerStartPrefix = "# DevPod Start "
MarkerEndPrefix = "# DevPod End "
)
func ConfigureSSHConfig(sshConfigPath, sshConfigIncludePath, context, workspace, user, workdir string, gpgagent bool, devPodHome string, log log.Logger) error {
return configureSSHConfigSameFile(sshConfigPath, sshConfigIncludePath, context, workspace, user, workdir, "", gpgagent, devPodHome, log)
}
func configureSSHConfigSameFile(sshConfigPath, sshConfigIncludePath, context, workspace, user, workdir, command string, gpgagent bool, devPodHome string, log log.Logger) error {
configLock.Lock()
defer configLock.Unlock()
targetPath := sshConfigPath
if sshConfigIncludePath != "" {
targetPath = sshConfigIncludePath
}
newFile, err := addHost(targetPath, workspace+"."+"devpod", user, context, workspace, workdir, command, gpgagent, devPodHome)
if err != nil {
return errors.Wrap(err, "parse ssh config")
}
return writeSSHConfig(targetPath, newFile, log)
}
type DevPodSSHEntry struct {
Host string
User string
Workspace string
}
func addHost(path, host, user, context, workspace, workdir, command string, gpgagent bool, devPodHome string) (string, error) {
newConfig, err := removeFromConfig(path, host)
if err != nil {
return "", err
}
// get path to executable
execPath, err := os.Executable()
if err != nil {
return "", err
}
return addHostSection(newConfig, execPath, host, user, context, workspace, workdir, command, gpgagent, devPodHome)
}
func addHostSection(config, execPath, host, user, context, workspace, workdir, command string, gpgagent bool, devPodHome string) (string, error) {
newLines := []string{}
// add new section
startMarker := MarkerStartPrefix + host
endMarker := MarkerEndPrefix + host
newLines = append(newLines, startMarker)
newLines = append(newLines, "Host "+host)
newLines = append(newLines, " ForwardAgent yes")
newLines = append(newLines, " LogLevel error")
newLines = append(newLines, " StrictHostKeyChecking no")
newLines = append(newLines, " UserKnownHostsFile /dev/null")
newLines = append(newLines, " HostKeyAlgorithms rsa-sha2-256,rsa-sha2-512,ssh-rsa")
proxyCommand := ""
if command != "" {
proxyCommand = fmt.Sprintf(" ProxyCommand \"%s\"", command)
} else {
proxyCommand = fmt.Sprintf(" ProxyCommand \"%s\" ssh --stdio --context %s --user %s %s", execPath, context, user, workspace)
}
if devPodHome != "" {
proxyCommand = fmt.Sprintf("%s --devpod-home \"%s\"", proxyCommand, devPodHome)
}
if workdir != "" {
proxyCommand = fmt.Sprintf("%s --workdir \"%s\"", proxyCommand, workdir)
}
if gpgagent {
proxyCommand = fmt.Sprintf("%s --gpg-agent-forwarding", proxyCommand)
}
newLines = append(newLines, proxyCommand)
newLines = append(newLines, " User "+user)
newLines = append(newLines, endMarker)
// now we append the original config
// keep our blocks on top of the hosts for priority reasons, but below any includes
lineNumber := 0
found := false
lines := []string{}
commentLines := 0
scanner := bufio.NewScanner(strings.NewReader(config))
for scanner.Scan() {
line := scanner.Text()
// Check `Host` keyword
if strings.HasPrefix(strings.TrimSpace(line), "Host") && !found {
found = true
lineNumber = max(lineNumber-commentLines, 0)
}
// Preserve comments
if strings.HasPrefix(strings.TrimSpace(line), "#") {
commentLines++
} else {
commentLines = 0
}
if !found {
lineNumber++
}
lines = append(lines, line)
}
if err := scanner.Err(); err != nil {
return config, err
}
lines = slices.Insert(lines, lineNumber, newLines...)
newLineSep := "\n"
if runtime.GOOS == "windows" {
newLineSep = "\r\n"
}
return strings.Join(lines, newLineSep), nil
}
func GetUser(workspaceID string, sshConfigPath string) (string, error) {
path, err := ResolveSSHConfigPath(sshConfigPath)
if err != nil {
return "", errors.Wrap(err, "Invalid ssh config path")
}
sshConfigPath = path
user := "root"
_, err = transformHostSection(sshConfigPath, workspaceID+"."+"devpod", func(line string) string {
splitted := strings.Split(strings.ToLower(strings.TrimSpace(line)), " ")
if len(splitted) == 2 && splitted[0] == "user" {
user = strings.Trim(splitted[1], "\"")
}
return line
})
if err != nil {
return "", err
}
return user, nil
}
func RemoveFromConfig(workspaceID string, sshConfigPath string, sshConfigIncludePath string, log log.Logger) error {
configLock.Lock()
defer configLock.Unlock()
targetPath := sshConfigPath
if sshConfigIncludePath != "" {
targetPath = sshConfigIncludePath
}
newFile, err := removeFromConfig(targetPath, workspaceID+"."+"devpod")
if err != nil {
return errors.Wrap(err, "parse ssh config")
}
return writeSSHConfig(targetPath, newFile, log)
}
func writeSSHConfig(path, content string, log log.Logger) error {
err := os.MkdirAll(filepath.Dir(path), 0755)
if err != nil {
log.Debugf("error creating ssh directory: %v", err)
}
err = os.WriteFile(path, []byte(content), 0600)
if err != nil {
return errors.Wrap(err, "write ssh config")
}
return nil
}
func ResolveSSHConfigPath(sshConfigPath string) (string, error) {
homeDir, err := util.UserHomeDir()
if err != nil {
return "", errors.Wrap(err, "get home dir")
}
if sshConfigPath == "" {
return filepath.Join(homeDir, ".ssh", "config"), nil
}
if strings.HasPrefix(sshConfigPath, "~/") {
sshConfigPath = strings.Replace(sshConfigPath, "~", homeDir, 1)
}
return filepath.Abs(sshConfigPath)
}
func removeFromConfig(path, host string) (string, error) {
return transformHostSection(path, host, func(line string) string {
return ""
})
}
func transformHostSection(path, host string, transform func(line string) string) (string, error) {
var reader io.Reader
f, err := os.Open(path)
if err != nil {
if !os.IsNotExist(err) {
return "", err
}
reader = strings.NewReader("")
} else {
reader = f
defer f.Close()
}
configScanner := scanner.NewScanner(reader)
newLines := []string{}
inSection := false
startMarker := MarkerStartPrefix + host
endMarker := MarkerEndPrefix + host
for configScanner.Scan() {
text := configScanner.Text()
if strings.HasPrefix(text, startMarker) {
inSection = true
} else if strings.HasPrefix(text, endMarker) {
inSection = false
} else if !inSection {
newLines = append(newLines, text)
} else if inSection {
text = transform(text)
if text != "" {
newLines = append(newLines, text)
}
}
}
if configScanner.Err() != nil {
return "", errors.Wrap(err, "parse ssh config")
}
// remove residual empty line at start file
if len(newLines) > 0 && newLines[0] == "" {
newLines = newLines[1:]
}
return strings.Join(newLines, "\n"), nil
}