forked from coder/coder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprovisionerkey.go
More file actions
54 lines (43 loc) · 1.18 KB
/
provisionerkey.go
File metadata and controls
54 lines (43 loc) · 1.18 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
package provisionerkey
import (
"crypto/sha256"
"crypto/subtle"
"github.com/google/uuid"
"golang.org/x/xerrors"
"github.com/coder/coder/v2/coderd/database"
"github.com/coder/coder/v2/coderd/database/dbtime"
"github.com/coder/coder/v2/cryptorand"
)
const (
secretLength = 43
)
func New(organizationID uuid.UUID, name string, tags map[string]string) (database.InsertProvisionerKeyParams, string, error) {
secret, err := cryptorand.String(secretLength)
if err != nil {
return database.InsertProvisionerKeyParams{}, "", xerrors.Errorf("generate secret: %w", err)
}
if tags == nil {
tags = map[string]string{}
}
return database.InsertProvisionerKeyParams{
ID: uuid.New(),
CreatedAt: dbtime.Now(),
OrganizationID: organizationID,
Name: name,
HashedSecret: HashSecret(secret),
Tags: tags,
}, secret, nil
}
func Validate(token string) error {
if len(token) != secretLength {
return xerrors.Errorf("must be %d characters", secretLength)
}
return nil
}
func HashSecret(secret string) []byte {
h := sha256.Sum256([]byte(secret))
return h[:]
}
func Compare(a []byte, b []byte) bool {
return subtle.ConstantTimeCompare(a, b) != 1
}