forked from loft-sh/devpod
-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathssh.go
More file actions
793 lines (712 loc) · 21.7 KB
/
ssh.go
File metadata and controls
793 lines (712 loc) · 21.7 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
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
package cmd
import (
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path"
"strings"
"time"
"al.essio.dev/pkg/shellescape"
"github.com/sirupsen/logrus"
"github.com/skevetter/devpod/cmd/completion"
"github.com/skevetter/devpod/cmd/flags"
"github.com/skevetter/devpod/cmd/machine"
"github.com/skevetter/devpod/pkg/agent"
client2 "github.com/skevetter/devpod/pkg/client"
"github.com/skevetter/devpod/pkg/client/clientimplementation"
"github.com/skevetter/devpod/pkg/config"
"github.com/skevetter/devpod/pkg/gpg"
"github.com/skevetter/devpod/pkg/port"
"github.com/skevetter/devpod/pkg/provider"
devssh "github.com/skevetter/devpod/pkg/ssh"
"github.com/skevetter/devpod/pkg/tunnel"
workspace2 "github.com/skevetter/devpod/pkg/workspace"
"github.com/skevetter/log"
"github.com/spf13/cobra"
"golang.org/x/crypto/ssh"
)
const (
DisableSSHKeepAlive time.Duration = 0 * time.Second
)
// SSHCmd holds the ssh cmd flags.
type SSHCmd struct {
*flags.GlobalFlags
ForwardPortsTimeout string
ForwardPorts []string
ReverseForwardPorts []string
SendEnvVars []string
SetEnvVars []string
Stdio bool
JumpContainer bool
ReuseSSHAuthSock string
AgentForwarding bool
GPGAgentForwarding bool
GitSSHSignatureForwarding bool
GitSSHSigningKey string
// ssh keepalive options
SSHKeepAliveInterval time.Duration `json:"sshKeepAliveInterval,omitempty"`
StartServices bool
TermMode string
InstallTerminfo bool
Command string
User string
WorkDir string
}
// NewSSHCmd creates a new ssh command.
func NewSSHCmd(f *flags.GlobalFlags) *cobra.Command {
cmd := &SSHCmd{
GlobalFlags: f,
}
sshCmd := &cobra.Command{
Use: "ssh [flags] [workspace-folder|workspace-name]",
Short: "Starts a new ssh session to a workspace",
RunE: func(cobraCmd *cobra.Command, args []string) error {
devPodConfig, err := config.LoadConfig(cmd.Context, cmd.Provider)
if err != nil {
return err
}
localOnly := cmd.Stdio
ctx := cobraCmd.Context()
client, err := workspace2.Get(ctx, workspace2.GetOptions{
DevPodConfig: devPodConfig,
Args: args,
ChangeLastUsed: true,
Owner: cmd.Owner,
LocalOnly: localOnly,
Log: log.Default.ErrorStreamOnly(),
})
if err != nil {
return err
}
return cmd.Run(ctx, devPodConfig, client, log.Default.ErrorStreamOnly())
},
ValidArgsFunction: func(rootCmd *cobra.Command, args []string, toComplete string) ([]string, cobra.ShellCompDirective) {
return completion.GetWorkspaceSuggestions(
rootCmd,
cmd.Context,
cmd.Provider,
args,
toComplete,
cmd.Owner,
log.Default,
)
},
}
sshCmd.Flags().
StringArrayVarP(&cmd.ForwardPorts, "forward-ports", "L", []string{},
"Specifies that connections to the given TCP port or Unix socket on the local (client) "+
"host are to be forwarded to the given host and port, or Unix socket, on the remote side.")
sshCmd.Flags().
StringArrayVarP(&cmd.ReverseForwardPorts, "reverse-forward-ports", "R", []string{},
"Specifies that connections to the given TCP port or Unix socket on the local (client) "+
"host are to be reverse forwarded to the given host and port, or Unix socket, on the remote side.")
sshCmd.Flags().
StringArrayVarP(&cmd.SendEnvVars, "send-env", "", []string{},
"Specifies which local env variables shall be sent to the container.")
sshCmd.Flags().
StringArrayVarP(&cmd.SetEnvVars, "set-env", "", []string{}, "Specifies env variables to be set in the container.")
sshCmd.Flags().
StringVar(&cmd.ForwardPortsTimeout, "forward-ports-timeout", "",
"Specifies the timeout after which the command should terminate when the ports are unused.")
sshCmd.Flags().
StringVar(&cmd.Command, "command", "", "The command to execute within the workspace")
sshCmd.Flags().StringVar(&cmd.User, "user", "", "The user of the workspace to use")
sshCmd.Flags().StringVar(&cmd.WorkDir, "workdir", "", "The working directory in the container")
sshCmd.Flags().
BoolVar(&cmd.AgentForwarding, "agent-forwarding", true, "If true forward the local ssh keys to the remote machine")
sshCmd.Flags().
StringVar(&cmd.ReuseSSHAuthSock, "reuse-ssh-auth-sock", "",
"If set, the SSH_AUTH_SOCK is expected to already be available in the workspace "+
"(under /tmp using the key provided) and the connection reuses this instead of creating a new one")
_ = sshCmd.Flags().MarkHidden("reuse-ssh-auth-sock")
sshCmd.Flags().
BoolVar(&cmd.GPGAgentForwarding, "gpg-agent-forwarding", false,
"If true forward the local gpg-agent to the remote machine")
sshCmd.Flags().
BoolVar(&cmd.Stdio, "stdio", false, "If true will tunnel connection through stdout and stdin")
sshCmd.Flags().
BoolVar(&cmd.StartServices, "start-services", true,
"If false will not start any port-forwarding or git / docker credentials helper")
sshCmd.Flags().
DurationVar(&cmd.SSHKeepAliveInterval, "ssh-keepalive-interval", 55*time.Second,
"How often should keepalive request be made (55s)")
sshCmd.Flags().
StringVar(&cmd.GitSSHSigningKey, "git-ssh-signing-key", "",
"The SSH signing key to use for git commit signing inside the workspace")
sshCmd.Flags().StringVar(
&cmd.TermMode,
"term-mode",
machine.TermModeAuto,
"PTY TERM selection mode: auto, strict, fallback",
)
sshCmd.Flags().BoolVar(
&cmd.InstallTerminfo,
"install-terminfo",
false,
"Install local TERM terminfo on remote before PTY",
)
return sshCmd
}
// Run runs the command logic.
func (cmd *SSHCmd) Run(
ctx context.Context,
devPodConfig *config.Config,
client client2.BaseWorkspaceClient,
log log.Logger,
) error {
// add ssh keys to agent
if devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == config.BoolTrue &&
devPodConfig.ContextOption(config.ContextOptionSSHAddPrivateKeys) == config.BoolTrue {
log.Debug(
"adding ssh keys to agent, disable via 'devpod context set-options -o SSH_ADD_PRIVATE_KEYS=false'",
)
err := devssh.AddPrivateKeysToAgent(ctx, log)
if err != nil {
log.Debugf("Error adding private keys to ssh-agent: %v", err)
}
}
// get user
if cmd.User == "" {
var err error
cmd.User, err = devssh.GetUser(
client.WorkspaceConfig().ID,
client.WorkspaceConfig().SSHConfigPath,
client.WorkspaceConfig().SSHConfigIncludePath,
)
if err != nil {
return err
}
}
// set default context if needed
if cmd.Context == "" {
cmd.Context = devPodConfig.DefaultContext
}
workspaceClient, ok := client.(client2.WorkspaceClient)
if ok {
return cmd.jumpContainer(ctx, devPodConfig, workspaceClient, log)
}
proxyClient, ok := client.(client2.ProxyClient)
if ok {
return cmd.startProxyTunnel(ctx, devPodConfig, proxyClient, log)
}
daemonClient, ok := client.(client2.DaemonClient)
if ok {
return cmd.jumpContainerTailscale(ctx, devPodConfig, daemonClient, log)
}
return nil
}
func (cmd *SSHCmd) jumpContainerTailscale(
ctx context.Context,
devPodConfig *config.Config,
client client2.DaemonClient,
log log.Logger,
) error {
log.Debugf("Starting tailscale connection")
err := client.CheckWorkspaceReachable(ctx)
if err != nil {
return err
}
toolSSHClient, sshClient, err := client.SSHClients(ctx, cmd.User)
if err != nil {
return err
}
defer func() { _ = toolSSHClient.Close() }()
defer func() { _ = sshClient.Close() }()
// Forward ports if specified
if len(cmd.ForwardPorts) > 0 {
return cmd.forwardPorts(ctx, toolSSHClient, log)
}
// Reverse forward ports if specified
if len(cmd.ReverseForwardPorts) > 0 && !cmd.GPGAgentForwarding {
return cmd.reverseForwardPorts(ctx, toolSSHClient, log)
}
if cmd.StartServices {
go func() {
err = clientimplementation.StartServicesDaemon(
ctx,
clientimplementation.StartServicesDaemonOptions{
DevPodConfig: devPodConfig,
Client: client,
SSHClient: toolSSHClient,
User: cmd.User,
Log: log,
ForwardPorts: false,
ExtraPorts: nil,
},
)
if err != nil {
log.Errorf("Error starting services: %v", err)
}
}()
}
// Handle GPG agent forwarding
if cmd.GPGAgentForwarding ||
devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == config.BoolTrue {
if gpg.IsGpgTunnelRunning(ctx, cmd.User, toolSSHClient, log) {
log.Debugf("[GPG] exporting already running, skipping")
} else if err := cmd.setupGPGAgent(ctx, toolSSHClient, log); err != nil {
return err
}
}
// Handle ssh stdio mode
if cmd.Stdio {
if cmd.SSHKeepAliveInterval != DisableSSHKeepAlive {
go startSSHKeepAlive(ctx, toolSSHClient, cmd.SSHKeepAliveInterval, log)
}
return client.DirectTunnel(ctx, os.Stdin, os.Stdout)
}
// Connect to the inner server and handle user session
return machine.RunSSHSession(
ctx,
sshClient,
machine.RunSSHSessionOptions{
AgentForwarding: cmd.AgentForwarding,
Command: cmd.Command,
SessionOptions: machine.SSHSessionOptions{
TermMode: cmd.TermMode,
InstallTerminfo: cmd.InstallTerminfo,
},
Stderr: os.Stderr,
},
)
}
func (cmd *SSHCmd) startProxyTunnel(
ctx context.Context,
devPodConfig *config.Config,
client client2.ProxyClient,
log log.Logger,
) error {
log.Debugf("Start proxy tunnel")
return tunnel.NewTunnel(
ctx,
func(ctx context.Context, stdin io.Reader, stdout io.Writer) error {
return client.Ssh(ctx, client2.SshOptions{
User: cmd.User,
Stdin: stdin,
Stdout: stdout,
})
},
func(ctx context.Context, containerClient *ssh.Client) error {
return cmd.startTunnel(ctx, devPodConfig, containerClient, client, log)
},
)
}
func (cmd *SSHCmd) retrieveEnVars() (map[string]string, error) {
envVars := make(map[string]string)
for _, envVar := range cmd.SendEnvVars {
envVarValue, exist := os.LookupEnv(envVar)
if exist {
envVars[envVar] = envVarValue
}
}
for _, envVar := range cmd.SetEnvVars {
parts := strings.Split(envVar, "=")
if len(parts) != 2 {
return nil, fmt.Errorf("invalid env var: %s", envVar)
}
envVars[parts[0]] = parts[1]
}
return envVars, nil
}
func (cmd *SSHCmd) jumpContainer(
ctx context.Context,
devPodConfig *config.Config,
client client2.WorkspaceClient,
log log.Logger,
) error {
// lock the workspace as long as we init the connection
err := client.Lock(ctx)
if err != nil {
return err
}
defer client.Unlock()
// start the workspace
err = clientimplementation.StartWait(ctx, client, false, log)
if err != nil {
return err
}
envVars, err := cmd.retrieveEnVars()
if err != nil {
return err
}
// tunnel to container
return tunnel.NewContainerTunnel(client, log).
Run(ctx, func(ctx context.Context, containerClient *ssh.Client) error {
// we have a connection to the container, make sure others can connect as well
client.Unlock()
// start ssh tunnel
return cmd.startTunnel(ctx, devPodConfig, containerClient, client, log)
}, devPodConfig, envVars)
}
func (cmd *SSHCmd) forwardTimeout(log log.Logger) (time.Duration, error) {
timeout := time.Duration(0)
if cmd.ForwardPortsTimeout != "" {
timeout, err := time.ParseDuration(cmd.ForwardPortsTimeout)
if err != nil {
return timeout, fmt.Errorf("parse forward ports timeout: %w", err)
}
log.Infof("Using port forwarding timeout of %s", cmd.ForwardPortsTimeout)
}
return timeout, nil
}
func (cmd *SSHCmd) reverseForwardPorts(
ctx context.Context,
containerClient *ssh.Client,
log log.Logger,
) error {
timeout, err := cmd.forwardTimeout(log)
if err != nil {
return fmt.Errorf("parse forward ports timeout: %w", err)
}
errChan := make(chan error, len(cmd.ReverseForwardPorts))
for _, portMapping := range cmd.ReverseForwardPorts {
mapping, err := port.ParsePortSpec(portMapping)
if err != nil {
return fmt.Errorf("parse port mapping: %w", err)
}
// start the forwarding
log.Infof(
"Reverse forwarding local %s/%s to remote %s/%s",
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
)
go func(portMapping string) {
err := devssh.ReversePortForward(
ctx,
containerClient,
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
timeout,
log,
)
if !errors.Is(io.EOF, err) {
errChan <- fmt.Errorf("error forwarding %s: %w", portMapping, err)
}
}(portMapping)
}
return <-errChan
}
func (cmd *SSHCmd) forwardPorts(
ctx context.Context,
containerClient *ssh.Client,
log log.Logger,
) error {
timeout, err := cmd.forwardTimeout(log)
if err != nil {
return fmt.Errorf("parse forward ports timeout: %w", err)
}
errChan := make(chan error, len(cmd.ForwardPorts))
for _, portMapping := range cmd.ForwardPorts {
mapping, err := port.ParsePortSpec(portMapping)
if err != nil {
return fmt.Errorf("parse port mapping: %w", err)
}
// start the forwarding
log.Infof(
"Forwarding local %s/%s to remote %s/%s",
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
)
go func(portMapping string) {
err := devssh.PortForward(
ctx,
containerClient,
mapping.Host.Protocol,
mapping.Host.Address,
mapping.Container.Protocol,
mapping.Container.Address,
timeout,
log,
)
if !errors.Is(io.EOF, err) {
errChan <- fmt.Errorf("error forwarding %s: %w", portMapping, err)
}
}(portMapping)
}
return <-errChan
}
func (cmd *SSHCmd) startTunnel(
ctx context.Context,
devPodConfig *config.Config,
containerClient *ssh.Client,
workspaceClient client2.BaseWorkspaceClient,
log log.Logger,
) error {
// check if we should forward ports
if len(cmd.ForwardPorts) > 0 {
return cmd.forwardPorts(ctx, containerClient, log)
}
// check if we should reverse forward ports
if len(cmd.ReverseForwardPorts) > 0 && !cmd.GPGAgentForwarding {
return cmd.reverseForwardPorts(ctx, containerClient, log)
}
if cmd.StartServices {
configureDockerCredentials := devPodConfig.ContextOption(
config.ContextOptionSSHInjectDockerCredentials,
) == config.BoolTrue
configureGitCredentials := devPodConfig.ContextOption(
config.ContextOptionSSHInjectGitCredentials,
) == config.BoolTrue
configureGitSSHSignatureHelper := devPodConfig.ContextOption(
config.ContextOptionGitSSHSignatureForwarding,
) == config.BoolTrue
go cmd.startServices(
ctx,
devPodConfig,
containerClient,
workspaceClient.WorkspaceConfig(),
configureDockerCredentials,
configureGitCredentials,
configureGitSSHSignatureHelper,
cmd.GitSSHSigningKey,
log,
)
}
// start ssh
writer := log.ErrorStreamOnly().Writer(logrus.InfoLevel, false)
defer func() { _ = writer.Close() }()
// check if we should do gpg agent forwarding
if cmd.GPGAgentForwarding ||
devPodConfig.ContextOption(config.ContextOptionGPGAgentForwarding) == config.BoolTrue {
// Check if a forwarding is already enabled and running, in that case
// we skip the forwarding and keep using the original one
if gpg.IsGpgTunnelRunning(ctx, cmd.User, containerClient, log) {
log.Debugf("[GPG] exporting already running, skipping")
} else {
err := cmd.setupGPGAgent(ctx, containerClient, log)
if err != nil {
return err
}
}
}
workdir := resolveWorkdir(cmd.WorkDir, workspaceClient, log)
log.Debugf("Run outer container tunnel")
commandArgs := []string{
agent.ContainerDevPodHelperLocation,
"helper",
"ssh-server",
"--track-activity",
"--stdio",
"--workdir",
workdir,
}
if cmd.ReuseSSHAuthSock != "" {
log.Debug("Reusing SSH_AUTH_SOCK")
commandArgs = append(commandArgs, "--reuse-ssh-auth-sock", cmd.ReuseSSHAuthSock)
}
if cmd.Debug {
commandArgs = append(commandArgs, "--debug")
}
command := shellescape.QuoteCommand(commandArgs)
if cmd.User != "" && cmd.User != "root" {
command = shellescape.QuoteCommand([]string{"su", "-c", command, cmd.User})
}
envVars, err := cmd.retrieveEnVars()
if err != nil {
return err
}
// Traffic is coming in from the outside, we need to forward it to the container
if cmd.Stdio {
return devssh.Run(ctx, devssh.RunOptions{
Client: containerClient,
Command: command,
Stdin: os.Stdin,
Stdout: os.Stdout,
Stderr: writer,
EnvVars: envVars,
})
}
return machine.StartSSHSession(ctx, machine.StartSSHSessionOptions{
User: cmd.User,
Command: cmd.Command,
AgentForwarding: cmd.AgentForwarding &&
devPodConfig.ContextOption(config.ContextOptionSSHAgentForwarding) == config.BoolTrue,
SessionOptions: machine.SSHSessionOptions{
TermMode: cmd.TermMode,
InstallTerminfo: cmd.InstallTerminfo,
},
Exec: func(ctx context.Context, stdin io.Reader, stdout io.Writer, stderr io.Writer) error {
if cmd.SSHKeepAliveInterval != DisableSSHKeepAlive {
go startSSHKeepAlive(ctx, containerClient, cmd.SSHKeepAliveInterval, log)
}
return devssh.Run(ctx, devssh.RunOptions{
Client: containerClient,
Command: command,
Stdin: stdin,
Stdout: stdout,
Stderr: stderr,
EnvVars: envVars,
})
},
Stderr: writer,
})
}
func resolveWorkdir(
workdir string,
workspaceClient client2.BaseWorkspaceClient,
log log.Logger,
) string {
if workdir != "" {
return workdir
}
if workspaceFolder := resolveMergedWorkspaceFolder(
workspaceClient,
log,
); workspaceFolder != "" {
return workspaceFolder
}
return path.Join("/workspaces", workspaceClient.Workspace())
}
func resolveMergedWorkspaceFolder(
workspaceClient client2.BaseWorkspaceClient,
log log.Logger,
) string {
workspaceConfig := workspaceClient.WorkspaceConfig()
if workspaceConfig == nil || workspaceConfig.Context == "" || workspaceConfig.ID == "" {
return ""
}
result, err := provider.LoadWorkspaceResult(workspaceConfig.Context, workspaceConfig.ID)
if err != nil {
log.Debugf("Error loading workspace result for workdir resolution: %v", err)
return ""
}
if result == nil || result.MergedConfig == nil {
return ""
}
return result.MergedConfig.WorkspaceFolder
}
func (cmd *SSHCmd) startServices(
ctx context.Context,
devPodConfig *config.Config,
containerClient *ssh.Client,
workspace *provider.Workspace,
configureDockerCredentials, configureGitCredentials, configureGitSSHSignatureHelper bool,
gitSSHSigningKey string,
log log.Logger,
) {
if cmd.User != "" {
err := tunnel.RunServices(
ctx,
tunnel.RunServicesOptions{
DevPodConfig: devPodConfig,
ContainerClient: containerClient,
User: cmd.User,
ForwardPorts: false,
ExtraPorts: nil,
PlatformOptions: nil,
Workspace: workspace,
ConfigureDockerCredentials: configureDockerCredentials,
ConfigureGitCredentials: configureGitCredentials,
ConfigureGitSSHSignatureHelper: configureGitSSHSignatureHelper,
GitSSHSigningKey: gitSSHSigningKey,
Log: log,
},
)
if err != nil {
log.Debugf("Error running credential server: %v", err)
}
}
}
// setupGPGAgent will forward a local gpg-agent into the remote container
// this works by using cmd/agent/workspace/setup_gpg.
func (cmd *SSHCmd) setupGPGAgent(
ctx context.Context,
containerClient *ssh.Client,
log log.Logger,
) error {
log.Debugf("[GPG] exporting gpg owner trust from host")
ownerTrustExport, err := gpg.GetHostOwnerTrust()
if err != nil {
return fmt.Errorf("export local ownertrust from GPG: %w", err)
}
ownerTrustArgument := base64.StdEncoding.EncodeToString(ownerTrustExport)
log.Debugf("[GPG] detecting gpg-agent socket path on host")
// Detect local agent extra socket, this will be forwarded to the remote and
// symlinked in multiple paths
gpgExtraSocketBytes, err := exec.Command("gpgconf", []string{"--list-dir", "agent-extra-socket"}...).
Output()
if err != nil {
return err
}
gpgExtraSocketPath := strings.TrimSpace(string(gpgExtraSocketBytes))
log.Debugf("[GPG] detected gpg-agent socket path %s", gpgExtraSocketPath)
gitGpgKey, err := exec.Command("git", []string{"config", "user.signingKey"}...).Output()
if err != nil {
log.Debugf("[GPG] no git signkey detected, skipping")
} else {
log.Debugf("[GPG] detected git sign key %s", gitGpgKey)
}
cmd.ReverseForwardPorts = append(cmd.ReverseForwardPorts, gpgExtraSocketPath)
// Now we forward the agent socket to the remote, and setup remote gpg to use it
forwardAgent := []string{
agent.ContainerDevPodHelperLocation,
"agent",
"workspace",
"setup-gpg",
"--ownertrust",
ownerTrustArgument,
"--socketpath",
gpgExtraSocketPath,
}
if log.GetLevel() == logrus.DebugLevel {
forwardAgent = append(forwardAgent, "--debug")
}
if len(gitGpgKey) > 0 {
gitKey := strings.TrimSpace(string(gitGpgKey))
forwardAgent = append(forwardAgent, "--gitkey")
forwardAgent = append(forwardAgent, gitKey)
}
command := shellescape.QuoteCommand(forwardAgent)
if cmd.User != "" && cmd.User != "root" {
command = shellescape.QuoteCommand([]string{"su", "-c", command, cmd.User})
}
log.Debugf(
"[GPG] start reverse forward of gpg-agent socket %s, keeping connection open",
gpgExtraSocketPath,
)
go func() {
log.Error(cmd.reverseForwardPorts(ctx, containerClient, log))
}()
writer := log.ErrorStreamOnly().Writer(logrus.InfoLevel, false)
defer func() { _ = writer.Close() }()
err = devssh.Run(ctx, devssh.RunOptions{
Client: containerClient,
Command: command,
Stdout: writer,
Stderr: writer,
})
if err != nil {
return fmt.Errorf("run gpg agent setup command: %w", err)
}
return nil
}
func startSSHKeepAlive(
ctx context.Context,
client *ssh.Client,
interval time.Duration,
log log.Logger,
) {
ticker := time.NewTicker(interval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
_, _, err := client.SendRequest("keepalive@openssh.com", true, nil)
if err != nil {
log.Errorf("Failed to send keepalive: %w", err)
}
}
}
}