-
Notifications
You must be signed in to change notification settings - Fork 314
/
encoding.go
87 lines (76 loc) · 2.2 KB
/
encoding.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
package encoding
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
"strings"
"github.com/denisbrodbeck/machineid"
"github.com/google/uuid"
"github.com/loft-sh/log"
"github.com/mitchellh/go-homedir"
)
const (
// hashingKey is a random string used for hashing the UID.
// It shouldn't be changed after the release.
hashingKey = "2f1uR7n8ryzFEaAm87Ec"
)
const (
WorkspaceUIDLength = 16
MachineUIDLength = 40
)
func CreateNewUID(context, id string) string {
// this returns always a UID with length 16
uid := strings.ReplaceAll(uuid.New().String()+uuid.New().String(), "-", "")
return SafeConcatNameMax([]string{id, context, uid}, WorkspaceUIDLength)
}
func CreateNewUIDShort(id string) string {
// this returns always a UID with length 16
uid := strings.ReplaceAll(uuid.New().String()+uuid.New().String(), "-", "")[0:5]
return SafeConcatNameMax([]string{id, uid}, WorkspaceUIDLength)
}
func IsLegacyUID(uid string) bool {
return len(uid) != WorkspaceUIDLength && len(uid) != MachineUIDLength
}
func SafeConcatNameMax(name []string, max int) string {
fullPath := strings.Join(name, "-")
if len(fullPath) > max {
digest := sha256.Sum256([]byte(fullPath))
digestEncoded := hex.EncodeToString(digest[0:])
trimmedPath := fullPath[0 : max-6]
if strings.HasSuffix(trimmedPath, "-") {
trimmedPath += digestEncoded[0:6]
} else {
trimmedPath += "-" + digestEncoded[0:5]
}
return trimmedPath
}
return fullPath
}
func GetMachineUIDShort(log log.Logger) string {
return GetMachineUID(log)[0:5]
}
// Gets machine ID and encodes it together with users $HOME path and extra key to protect privacy.
// Returns a hex-encoded string.
func GetMachineUID(log log.Logger) string {
id, err := machineid.ID()
if err != nil {
id = "error"
if log != nil {
log.Debugf("Error retrieving machine uid: %v", err)
}
}
// get $HOME to distinguish two users on the same machine
// will be hashed later together with the ID
home, err := homedir.Dir()
if err != nil {
home = "error"
if log != nil {
log.Debugf("Error retrieving machine home: %v", err)
}
}
mac := hmac.New(sha256.New, []byte(id))
mac.Write([]byte(hashingKey))
mac.Write([]byte(home))
return fmt.Sprintf("%x", mac.Sum(nil))
}