Skip to content

Commit e9cfedd

Browse files
authored
Get SSH username from workspacekit (#19146)
* Get SSH username from workspacekit * Disable false positive * Check status code
1 parent 8ca0953 commit e9cfedd

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

components/ws-proxy/pkg/sshproxy/server.go

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,10 @@ package sshproxy
77
import (
88
"context"
99
"crypto/subtle"
10+
"fmt"
11+
"io"
1012
"net"
13+
"net/http"
1114
"regexp"
1215
"strings"
1316
"time"
@@ -301,6 +304,7 @@ func (s *Server) HandleConn(c net.Conn) {
301304
}
302305

303306
var key ssh.Signer
307+
//nolint:ineffassign
304308
userName := "gitpod"
305309

306310
session := &Session{
@@ -318,6 +322,13 @@ func (s *Server) HandleConn(c net.Conn) {
318322
}
319323

320324
session.WorkspacePrivateKey = key
325+
326+
// obtain the SSH username from workspacekit.
327+
workspacekitPort := "22998"
328+
userName, err = workspaceSSHUsername(ctx, wsInfo.IPAddress, workspacekitPort)
329+
if err != nil {
330+
log.WithField("instanceId", wsInfo.InstanceID).WithError(err).Warn("failed to retrieve the SSH username. Using the default.")
331+
}
321332
} else {
322333
key, userName, err = s.GetWorkspaceSSHKey(ctx, wsInfo.IPAddress, supervisorPort)
323334
if err != nil {
@@ -494,3 +505,27 @@ func (s *Server) Serve(l net.Listener) error {
494505
go s.HandleConn(conn)
495506
}
496507
}
508+
509+
func workspaceSSHUsername(ctx context.Context, workspaceIP string, workspacekitPort string) (string, error) {
510+
req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("http://%v:%v/ssh/username", workspaceIP, workspacekitPort), nil)
511+
if err != nil {
512+
return "", err
513+
}
514+
515+
resp, err := http.DefaultClient.Do(req)
516+
if err != nil {
517+
return "", err
518+
}
519+
defer resp.Body.Close()
520+
521+
result, err := io.ReadAll(resp.Body)
522+
if err != nil {
523+
return "", err
524+
}
525+
526+
if resp.StatusCode != http.StatusOK {
527+
return "", fmt.Errorf(fmt.Sprintf("unexpected status: %v (%v)", string(result), resp.StatusCode))
528+
}
529+
530+
return string(result), nil
531+
}

0 commit comments

Comments
 (0)