-
Notifications
You must be signed in to change notification settings - Fork 8
/
client.go
105 lines (86 loc) · 2.38 KB
/
client.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
// Copyright 2022 Namespace Labs Inc; All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
package ssh
import (
"context"
"encoding/base64"
"fmt"
"net"
"os"
"strings"
"golang.org/x/crypto/ssh"
"namespacelabs.dev/foundation/internal/console"
"namespacelabs.dev/foundation/internal/fnerrors"
"namespacelabs.dev/foundation/internal/tcache"
)
var (
sshTransports = tcache.NewCache[*ssh.Client]()
)
type Endpoint struct {
User string
PrivateKeyPath string
Address string
}
type Deferred struct {
CacheKey string
Dial func() (*ssh.Client, error)
}
func Establish(ctx context.Context, endpoint Endpoint) (*Deferred, error) {
debugLogger := console.Debug(ctx)
if endpoint.User == "" {
return nil, fnerrors.New("transport.ssh: user is required")
}
sshAddr := endpoint.Address
if sshAddr == "" {
return nil, fnerrors.New("transport.ssh: address is required")
}
// XXX use net.SplitHostPort()
if len(strings.SplitN(sshAddr, ":", 2)) == 1 {
sshAddr = fmt.Sprintf("%s:22", sshAddr)
}
var auths []ssh.AuthMethod
key, keyKey, err := parseAuth(endpoint.PrivateKeyPath)
if err != nil {
return nil, err
}
if key != nil {
auths = append(auths, key)
}
config := ssh.ClientConfig{
User: endpoint.User,
Auth: auths,
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
fmt.Fprintf(debugLogger, "ssh: connected to %q (%s)\n", hostname, remote)
return nil
},
}
cachekey := fmt.Sprintf("%s:%s@%s", endpoint.User, keyKey, endpoint.Address)
return &Deferred{
CacheKey: cachekey,
Dial: func() (*ssh.Client, error) {
return sshTransports.Compute(cachekey, func() (*ssh.Client, error) {
fmt.Fprintf(debugLogger, "ssh: will dial to %q\n", endpoint.Address)
return ssh.Dial("tcp", sshAddr, &config)
})
},
}, nil
}
func parseAuth(privateKeyPath string) (ssh.AuthMethod, string, error) {
if privateKeyPath != "" {
key, err := parsePrivateKey(privateKeyPath)
if err != nil {
return nil, "", err
}
keyKey := base64.RawStdEncoding.EncodeToString(key.PublicKey().Marshal())
return ssh.PublicKeys(key), keyKey, nil
}
return nil, "", nil
}
func parsePrivateKey(keyPath string) (ssh.Signer, error) {
buff, err := os.ReadFile(keyPath)
if err != nil {
return nil, err
}
return ssh.ParsePrivateKey(buff)
}