forked from loft-sh/devpod
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathconfig.go
More file actions
405 lines (338 loc) · 9.71 KB
/
config.go
File metadata and controls
405 lines (338 loc) · 9.71 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
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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
package ssh
import (
"bufio"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"slices"
"strings"
"sync"
"github.com/skevetter/devpod/pkg/util"
"github.com/skevetter/log"
"github.com/skevetter/log/scanner"
)
var configLock sync.Mutex
var (
MarkerStartPrefix = "# DevPod Start "
MarkerEndPrefix = "# DevPod End "
)
type SSHConfigParams struct {
SSHConfigPath string
SSHConfigIncludePath string
Context string
Workspace string
User string
Workdir string
Command string
GPGAgent bool
DevPodHome string
Provider string
Log log.Logger
}
func ConfigureSSHConfig(params SSHConfigParams) error {
configLock.Lock()
defer configLock.Unlock()
targetPath := params.SSHConfigPath
if params.SSHConfigIncludePath != "" {
targetPath = params.SSHConfigIncludePath
}
newFile, err := addHost(addHostParams{
path: targetPath,
host: params.Workspace + "." + "devpod",
user: params.User,
context: params.Context,
workspace: params.Workspace,
workdir: params.Workdir,
command: params.Command,
gpgagent: params.GPGAgent,
devPodHome: params.DevPodHome,
provider: params.Provider,
})
if err != nil {
return fmt.Errorf("parse ssh config %w", err)
}
return writeSSHConfig(targetPath, newFile, params.Log)
}
type DevPodSSHEntry struct {
Host string
User string
Workspace string
}
type addHostParams struct {
path string
host string
user string
context string
workspace string
workdir string
command string
gpgagent bool
devPodHome string
provider string
}
func addHost(params addHostParams) (string, error) {
newConfig, err := removeFromConfig(params.path, params.host)
if err != nil {
return "", err
}
// get path to executable
execPath, err := os.Executable()
if err != nil {
return "", err
}
return addHostSection(newConfig, execPath, params)
}
// proxyCommandBuilder builds SSH ProxyCommand strings
type proxyCommandBuilder struct {
baseCommand string
options []string
}
func newProxyCommandBuilder(execPath, context, user, workspace string) *proxyCommandBuilder {
return &proxyCommandBuilder{
baseCommand: fmt.Sprintf("\"%s\" ssh --stdio --context %s --user %s %s", execPath, context, user, workspace),
}
}
func (b *proxyCommandBuilder) withDevPodHome(home string) *proxyCommandBuilder {
if home != "" {
b.options = append(b.options, fmt.Sprintf("--devpod-home \"%s\"", home))
}
return b
}
func (b *proxyCommandBuilder) withWorkdir(workdir string) *proxyCommandBuilder {
if workdir != "" {
b.options = append(b.options, fmt.Sprintf("--workdir \"%s\"", workdir))
}
return b
}
func (b *proxyCommandBuilder) withGPGAgent(enabled bool) *proxyCommandBuilder {
if enabled {
b.options = append(b.options, "--gpg-agent-forwarding")
}
return b
}
func (b *proxyCommandBuilder) build() string {
if len(b.options) == 0 {
return " ProxyCommand " + b.baseCommand
}
return fmt.Sprintf(" ProxyCommand %s %s", b.baseCommand, strings.Join(b.options, " "))
}
// sshConfigBuilder builds SSH config entries
type sshConfigBuilder struct {
lines []string
}
func newSSHConfigBuilder(host string) *sshConfigBuilder {
return &sshConfigBuilder{
lines: []string{
MarkerStartPrefix + host,
"Host " + host,
},
}
}
func (b *sshConfigBuilder) addSSHOptions(provider string) *sshConfigBuilder {
b.lines = append(b.lines,
" ForwardAgent yes",
" LogLevel error",
" StrictHostKeyChecking no",
" UserKnownHostsFile /dev/null",
" HostKeyAlgorithms rsa-sha2-256,rsa-sha2-512,ssh-rsa",
)
// TODO: Make SSH timeout configurable per provider via provider options
// The ms-vscode-remote.remote-ssh extension times out after 15s by default
// This is insufficient for the aws AWS provider as it needs additional time to
// connect to the instance
//
// The SSH config ConnectTimeout overrides the VSCode Remote-SSH remote.SSH.connectTimeout setting
// https://github.com/microsoft/vscode-remote-release/issues/8519
if strings.Contains(provider, "aws") {
b.lines = append(b.lines, " ConnectTimeout 60")
}
return b
}
func (b *sshConfigBuilder) addProxyCommand(proxyCmd string) *sshConfigBuilder {
b.lines = append(b.lines, proxyCmd)
return b
}
func (b *sshConfigBuilder) addUser(user, host string) *sshConfigBuilder {
b.lines = append(b.lines, " User "+user, MarkerEndPrefix+host)
return b
}
func (b *sshConfigBuilder) build() []string {
return b.lines
}
// buildProxyCommand creates the ProxyCommand string
func buildProxyCommand(execPath string, params addHostParams) string {
if params.command != "" {
return fmt.Sprintf(" ProxyCommand \"%s\"", params.command)
}
return newProxyCommandBuilder(execPath, params.context, params.user, params.workspace).
withDevPodHome(params.devPodHome).
withWorkdir(params.workdir).
withGPGAgent(params.gpgagent).
build()
}
// buildSSHConfigLines creates the SSH config entry lines
func buildSSHConfigLines(params addHostParams, proxyCmd string) []string {
return newSSHConfigBuilder(params.host).
addSSHOptions(params.provider).
addProxyCommand(proxyCmd).
addUser(params.user, params.host).
build()
}
// findInsertPosition finds where to insert new SSH config entry
func findInsertPosition(config string) (int, []string, error) {
lineNumber := 0
found := false
lines := []string{}
commentLines := 0
scanner := bufio.NewScanner(strings.NewReader(config))
for scanner.Scan() {
line := scanner.Text()
if strings.HasPrefix(strings.TrimSpace(line), "Host") && !found {
found = true
lineNumber = max(lineNumber-commentLines, 0)
}
if strings.HasPrefix(strings.TrimSpace(line), "#") {
commentLines++
} else {
commentLines = 0
}
if !found {
lineNumber++
}
lines = append(lines, line)
}
if err := scanner.Err(); err != nil {
return 0, nil, err
}
return lineNumber, lines, nil
}
// mergeSSHConfig inserts new lines into existing config
func mergeSSHConfig(lines, newLines []string, position int) string {
merged := slices.Insert(lines, position, newLines...)
newLineSep := "\n"
if runtime.GOOS == "windows" {
newLineSep = "\r\n"
}
return strings.Join(merged, newLineSep)
}
func addHostSection(config, execPath string, params addHostParams) (string, error) {
proxyCmd := buildProxyCommand(execPath, params)
newLines := buildSSHConfigLines(params, proxyCmd)
position, lines, err := findInsertPosition(config)
if err != nil {
return config, err
}
return mergeSSHConfig(lines, newLines, position), nil
}
func GetUser(workspaceID string, sshConfigPath string, sshConfigIncludePath string) (string, error) {
path, err := ResolveSSHConfigPath(sshConfigPath)
if err != nil {
return "", fmt.Errorf("invalid ssh config path %w", err)
}
sshConfigPath = path
targetPath := sshConfigPath
if sshConfigIncludePath != "" {
includePath, err := ResolveSSHConfigPath(sshConfigIncludePath)
if err != nil {
return "", fmt.Errorf("invalid ssh config include path %w", err)
}
targetPath = includePath
}
user := "root"
_, err = transformHostSection(targetPath, 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 fmt.Errorf("parse ssh config %w", err)
}
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 fmt.Errorf("write ssh config %w", err)
}
return nil
}
func ResolveSSHConfigPath(sshConfigPath string) (string, error) {
homeDir, err := util.UserHomeDir()
if err != nil {
return "", fmt.Errorf("get home dir %w", err)
}
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 func() { _ = 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 "", fmt.Errorf("parse ssh config %w", err)
}
// remove residual empty line at start file
if len(newLines) > 0 && newLines[0] == "" {
newLines = newLines[1:]
}
return strings.Join(newLines, "\n"), nil
}