-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathattach.go
More file actions
98 lines (81 loc) · 2.6 KB
/
attach.go
File metadata and controls
98 lines (81 loc) · 2.6 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
package deskconn
import (
"encoding/json"
"fmt"
"os"
"strings"
"github.com/xconnio/wampproto-go/auth"
"github.com/xconnio/xconn-go"
)
const (
Realm = "io.xconn.deskconn"
ProcedureDeskconnAttachDesktop = "io.xconn.deskconn.desktop.attach"
ProcedureDeskconnDetachDesktop = "io.xconn.deskconn.desktop.detach"
ProcedureDeskconnOrganizationList = "io.xconn.deskconn.organization.list"
ProcedureOrganizationCreate = "io.xconn.deskconn.organization.create"
TopicDeskconnDesktopDetachFormat = "io.xconn.deskconn.desktop.%s.detach"
MachineIDPath = "/etc/machine-id"
)
func CloudURI() string {
if v, ok := os.LookupEnv("DESKCONN_CLOUD_URI"); ok {
return v
}
return "wss://api.deskconn.com/ws"
}
type Credentials struct {
Realm string `json:"realm"`
AuthID string `json:"authid"`
PublicKey string `json:"public_key"`
PrivateKey string `json:"private_key"` // #nosec
OrganizationID string `json:"organization_id"`
}
func Attach(session *xconn.Session, desktopName, orgID string) error {
machineID, err := os.ReadFile(MachineIDPath)
if err != nil {
return fmt.Errorf("failed to read machine-id: %w", err)
}
machineIDStr := strings.TrimSpace(string(machineID))
publicKey, privateKey, err := auth.GenerateCryptoSignKeyPair()
if err != nil {
return fmt.Errorf("failed to generate cryptosign keypair: %w", err)
}
callResp := session.Call(ProcedureDeskconnAttachDesktop).Args(machineIDStr, publicKey, orgID, desktopName).Do()
if callResp.Err != nil {
return fmt.Errorf("failed to attach desktop: %w", callResp.Err)
}
respDict, err := callResp.ArgDict(0)
if err != nil {
return err
}
id, err := respDict.String("realm")
if err != nil {
return err
}
return writeCredentialsFile(id, machineIDStr, publicKey, privateKey, orgID)
}
func Detach(session *xconn.Session, authID string) error {
callResp := session.Call(ProcedureDeskconnDetachDesktop).Args(authID).Do()
if callResp.Err != nil {
return fmt.Errorf("failed to detach desktop: %w", callResp.Err)
}
return nil
}
func writeCredentialsFile(realm, machineID, publicKey, privateKey, orgID string) error {
credFilePath, err := CredentialsFilePath()
if err != nil {
return err
}
creds := Credentials{
Realm: realm,
AuthID: machineID,
PublicKey: publicKey,
PrivateKey: privateKey,
OrganizationID: orgID,
}
data, err := json.MarshalIndent(creds, "", " ") // #nosec G117
if err != nil {
return fmt.Errorf("failed to marshal credentials: %w", err)
}
data = append(data, '\n')
return os.WriteFile(credFilePath, data, 0600)
}